Max Number of K-Sum Pairs - Solution

Time complexity - O(n)
Space complexity - O(n)

  1. Use unordered_map to store the frequency of elements.
  2. If (k-curr_element) exists , reduce the frequency and continue.
  3. return count
class Solution {
public:
    int maxOperations(vector<int>& nums, int k) {
        int count=0;
        int n=nums.size();
        unordered_map<int,int> um;
        for(int i=0;i<n;i++){
            if(um[k-nums[i]]>0){
                um[k-nums[i]]--;
                count++;
            }
            else
                um[nums[i]]++;
        }
        return count;
    }
};
Comments (0)