Max Number of K-Sum Pairs

medium array two pointers hash map

Problem

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.

Inputnums = [3, 1, 3, 4, 3], k = 6
Output1
Sorted: [1,3,3,3,4]. Pair (3, 3) sums to 6; only one such disjoint pair.

def max_operations(nums, k):
    nums.sort()
    l, r = 0, len(nums) - 1
    count = 0
    while l < r:
        s = nums[l] + nums[r]
        if s == k:
            count += 1; l += 1; r -= 1
        elif s < k: l += 1
        else: r -= 1
    return count
function maxOperations(nums, k) {
  nums.sort((a, b) => a - b);
  let l = 0, r = nums.length - 1, count = 0;
  while (l < r) {
    const s = nums[l] + nums[r];
    if (s === k) { count++; l++; r--; }
    else if (s < k) l++;
    else r--;
  }
  return count;
}
class Solution {
    public int maxOperations(int[] nums, int k) {
        Arrays.sort(nums);
        int l = 0, r = nums.length - 1, count = 0;
        while (l < r) {
            int s = nums[l] + nums[r];
            if (s == k) { count++; l++; r--; }
            else if (s < k) l++;
            else r--;
        }
        return count;
    }
}
int maxOperations(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int l = 0, r = (int)nums.size() - 1, count = 0;
    while (l < r) {
        int s = nums[l] + nums[r];
        if (s == k) { count++; l++; r--; }
        else if (s < k) l++;
        else r--;
    }
    return count;
}
Time: O(n log n) Space: O(1) beyond the sort