LeetCode: Max Number of K-Sum Pairs

Find the maximum number of k-sum pairs in an array.

Posted on LeetCode Python

See original problem on leetcode.com

Difficulty: Medium

Solution

I really 🩷 these two-pointer problems!

Start by sorting nums. Initialize count, left, and right.

If the sum of nums[left] and nums[right] is less than the target, then we need to make the smaller number bigger. Move left to the right.

If the sum of nums[left] and nums[right] is greater than the target, then we need to make the bigger number smaller. Move right to the left.

If the sum of nums[left] and nums[right] equals the target, increment count and move both pointers inward.

Runtime

493 ms | Beats 85.26%

class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
nums.sort()
count = 0
left, right = 0, len(nums) - 1
while left < right:
if nums[left] + nums[right] < k:
left += 1
elif nums[left] + nums[right] > k:
right -= 1
else:
count += 1
left += 1
right -= 1
return count