Skip to content

Commit f1fb728

Browse files
committed
Add solution for max k sum pairs
1 parent 3cd3fe3 commit f1fb728

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

two-pointer/k-sum-pairs/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# 1679. Max Number of K-Sum Pairs
2+
3+
## Description
4+
See https://leetcode.com/problems/max-number-of-k-sum-pairs/description/
5+
6+
## Problem
7+
You are given an integer array `nums` and an integer `k`.
8+
9+
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
10+
11+
Return the maximum number of operations you can perform on the array.
12+
13+
## Example 1
14+
15+
```
16+
Input: nums = [1,2,3,4], k = 5
17+
Output: 2
18+
Explanation: Starting with nums = [1,2,3,4]:
19+
- Remove numbers 1 and 4, then nums = [2,3]
20+
- Remove numbers 2 and 3, then nums = []
21+
There are no more pairs that sum up to 5, hence a total of 2 operations.
22+
```
23+
24+
## Example 2
25+
26+
```
27+
Input: nums = [3,1,3,4,3], k = 6
28+
Output: 1
29+
Explanation: Starting with nums = [3,1,3,4,3]:
30+
- Remove the first two 3's, then nums = [1,4,3]
31+
There are no more pairs that sum up to 6, hence a total of 1 operation.
32+
```
33+
34+
## Constraints
35+
36+
```
37+
1 <= nums.length <= 105
38+
1 <= nums[i] <= 109
39+
1 <= k <= 109
40+
```

two-pointer/k-sum-pairs/ksumpairs.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def max_operations(nums: list[int], k: int) -> int:
2+
i = 0
3+
j = len(nums) - 1
4+
count = 0
5+
nums.sort()
6+
while j > i:
7+
if nums[i] + nums[j] > k:
8+
j = j - 1
9+
elif nums[i] + nums[j] < k:
10+
i = i + 1
11+
else:
12+
count = count + 1
13+
nums[i] = nums[j] = 0
14+
i = i + 1
15+
j = j - 1
16+
return count
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from ksumpairs import max_operations
2+
3+
def test_example_1():
4+
nums = [1, 2, 3, 4]
5+
k = 5
6+
assert max_operations(nums, k) == 2
7+
8+
def test_example_2():
9+
nums = [3, 1, 3, 4, 3]
10+
k = 6
11+
assert max_operations(nums, k) == 1
12+
13+
def test_example_3():
14+
nums = [1, 2, 3, 4, 5, 6]
15+
k = 7
16+
assert max_operations(nums, k) == 3
17+
18+
def test_example_4():
19+
nums = [1, 1, 1, 1]
20+
k = 2
21+
assert max_operations(nums, k) == 2
22+
23+
def test_example_5():
24+
nums = [2, 2, 2, 2]
25+
k = 4
26+
assert max_operations(nums, k) == 2

0 commit comments

Comments
 (0)