π One-stop destination for all your technical interview Preparation π
You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
class Solution {
public:
int maxOperations(vector<int>& nums, int k)
{
int n = nums.size();
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == k) {
ans++;
// erase the elements from the array and reduce the size of by 2
nums.erase(nums.begin() + j);
nums.erase(nums.begin() + i);
n -= 2;
i--; // to check the element at i again
break;
}
}
}
return ans;
}
};
class Solution {
public:
int maxOperations(vector<int>& nums, int k)
{
int n = nums.size();
sort(nums.begin(), nums.end());
int i = 0, j = n - 1;
int ans = 0;
while (i < j) {
if (nums[i] + nums[j] < k)
i++;
else if (nums[i] + nums[j] > k)
j--;
else {
ans++;
i++;
j--;
}
}
return ans;
}
};
class Solution {
public:
int maxOperations(vector<int>& nums, int k)
{
unordered_map<int, int> mp;
int n = nums.size(), ans = 0;
for (int i = 0; i < n; i++) {
int num = k - nums[i];
if (mp[num] > 0) {
ans++;
mp[num]--; // pair found, decrease the frequency
} else {
mp[nums[i]]++; // pair not found, add the element to the map
}
}
return ans;
}
};