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 −
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))