Two Pointers· 25 min

Max Number of K-Sum Pairs

LeetCode #1679 · Medium · Interactive step-by-step visualization

Setup

Example inputnums = [1,2,3,4], k = 5
Step 1 / 7

Current step

1 / 7

Add 1 and 4. Sorted order tells you which direction moves the sum toward the target. Sum is 5; target is 5.

Step log

target

5

sum

5

pairs

0

Active cursor
Comparing
Best or completed
Leaving or removed
max-number-of-k-sum-pairs.java
1public int maxOperations(int[] nums, int k) {
2 Arrays.sort(nums);
3 int left = 0, right = nums.length - 1, pairs = 0;
4 while (left < right) {
5 int sum = nums[left] + nums[right];
6 if (sum == k) { pairs++; left++; right--; }
7 else if (sum < k) left++;
8 else right--;
9 }
10 return pairs;
11}
● Java
Time
O(n log n)
Space
O(log n)
Pattern
two pointers
Frames
7