Program to find max number of K-sum pairs in Python

Suppose we have an array called nums and another value k. In one operation, we can select two elements from nums whose sum equals k and remove them from the array. We have to find the maximum number of operations we can perform on the array.

So, if the input is like nums = [8,3,6,1,5] and k = 9, then the output will be 2 as we can delete [3,6] whose sum is 9, then remove [8,1] whose sum is also 9.

Algorithm

To solve this, we will follow these steps:

  • counter := a dictionary holding frequency of each item present in nums
  • result := 0
  • For each num in counter, do:
    • If counter[k-num] is non-zero, then:
      • If num is not same as k - num, then:
        • result := result + minimum of counter[num] and counter[k-num]
        • counter[k-num] := 0
        • counter[num] := 0
      • Otherwise:
        • result := result + quotient of (counter[num] / 2)
  • Return result

Example

Let us see the following implementation to get better understanding:

from collections import Counter

def solve(nums, k):
    counter = Counter(nums)
    result = 0
    
    for num in counter:
        if counter.get(k - num, 0):
            if num != k - num:
                result += min(counter[num], counter[k - num])
                counter[k - num] = 0
                counter[num] = 0
            else:
                result += int(counter[num] / 2)
    
    return result

nums = [8, 3, 6, 1, 5]
k = 9
print(solve(nums, k))
2

How It Works

The algorithm uses a frequency counter to track how many times each number appears. For each number, it checks if its complement (k - num) exists:

  • If num != k - num: We can pair different numbers, so we take the minimum count of both
  • If num == k - num: We need two identical numbers to form a pair, so we divide the count by 2

Another Example

Let's test with a different input where some numbers repeat:

from collections import Counter

def solve(nums, k):
    counter = Counter(nums)
    result = 0
    
    for num in counter:
        if counter.get(k - num, 0):
            if num != k - num:
                result += min(counter[num], counter[k - num])
                counter[k - num] = 0
                counter[num] = 0
            else:
                result += int(counter[num] / 2)
    
    return result

nums = [1, 2, 3, 4, 2, 2]
k = 4
print(f"Input: {nums}, k = {k}")
print(f"Output: {solve(nums, k)}")
Input: [1, 2, 3, 4, 2, 2], k = 4
Output: 2

Conclusion

This solution efficiently finds the maximum number of k-sum pairs using a frequency counter approach. The algorithm handles both cases where pairs are formed by different numbers and identical numbers, with a time complexity of O(n).

Updated on: 2026-03-26T14:11:42+05:30

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements