- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

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

- if num is not same as k - num, then

- if counter[k-num] is non-zero, then
- 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

- Related Articles
- Program to Find K-Largest Sum Pairs in Python
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Program to find max values of sublists of size k in Python
- Program to find number of good pairs in Python
- Program to find number of distinct combinations that sum up to k in python
- Program to find number of sublists with sum k in a binary list in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to count number of fraction pairs whose sum is 1 in python
- Program to find XOR sum of all pairs bitwise AND in Python
- Program to find sum of rectangle whose sum at most k in Python
- Program to count number of paths whose sum is k in python
- Program to find the sum of largest K sublist in Python
- Program to find sum of digits in base K using Python
- Program to find sum of differences between max and min elements from randomly selected k balls from n balls in Python
- Program to find lowest sum of pairs greater than given target in Python

Advertisements