Max Number of K-Sum Pairs

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.

30:00

Max Number of K-Sum Pairs
medium
Free written solution
Topics
Companies

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.

Example 1:
Input: {"nums":[1,2,3,4],"k":5}
Output: 2
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1091 \leq \text{nums}[i] \leq 10^9

  • 1≤k≤1091 \leq k \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,4],"k":5}

Find as many disjoint pairs as possible that add up to k = 5. First, sort the numbers.

nums (as given)

1
2
3
4
0
1
2
3

operations = 0

no pairs removed yet

Variables
VariableValue
k5
left0
right3
total-
ops0
DepthFunction Call
Stack empty
0/6