MediumNo. 1679
Max Number of K-Sum Pairs — LeetCode 1679 Python Solution
- Pattern
- Two Pointers
- Topics
- Array, Hash Table, Two Pointers, Sorting
- On a study list
- LeetCode 75
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [1,2,3,4], k = 5
- Output
- 2
- Explanation
- Starting with nums = [1,2,3,4]:
Python solution
class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
nums.sort()
l, r, ans = 0, len(nums) - 1, 0
while l < r:
s = nums[l] + nums[r]
if s == k:
ans += 1
l, r = l + 1, r - 1
elif s > k:
r -= 1
else:
l += 1
return ansComplexity
- Time
- O(n × log n)
- Space · auxiliary
- O(log n)
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1679. Max Number of K-Sum Pairs is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0349 | Intersection of Two Arrays | Easy |
| 0350 | Intersection of Two Arrays II | Easy |
| 0522 | Longest Uncommon Subsequence II | Medium |
| 0532 | K-diff Pairs in an Array | Medium |
| 0923 | 3Sum With Multiplicity | Medium |
| 1048 | Longest String Chain | Medium |
Frequently asked questions
- How hard is LeetCode 1679. Max Number of K-Sum Pairs?
LeetCode 1679. Max Number of K-Sum Pairs is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1679. Max Number of K-Sum Pairs?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 1679. Max Number of K-Sum Pairs?
The Python solution on this page uses O(log n) auxiliary space.
- What topics does LeetCode 1679. Max Number of K-Sum Pairs cover?
LeetCode 1679. Max Number of K-Sum Pairs is tagged Array, Hash Table, Two Pointers and Sorting on LeetCode.