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 is equals to 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] 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.

To solve this, we will follow these steps −

  • counter := a map holding frequency of each item present in nums
  • res := 0
  • for each num in counter, do
    • if counter[k-num] is non-zero, then
      • if num is not same as k - num, then
        • res := res + minimum of counter[num] and counter[k-num]
        • counter[k-num] := 0
        • counter[num] := 0
      • otherwise,
        • res := res + quotient of (counter[num] / 2)
  • return res

Example

Let us see the following implementation to get better understanding −

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

   return res

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

Input

[8,3,6,1,5], 9

Output

2

Updated on: 06-Oct-2021

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements