Max Number of K-Sum Pairs [Medium]

19 Sep 2026 2 min read
1
The Max Number of K-Sum Pairs problem requires finding the maximum number of pairs whose elements add up to a given target value.

Problem

Given an integer array nums and an integer k, return the maximum number of operations you can perform.

In each operation, choose two numbers whose sum is equal to k and remove them from the array.

Example(s)

Consider the following example(s) to understand the expected input and output.

Example 1

Input
nums = [1,2,3,4]
k = 5
Output
2

Example 2

Input
nums = [3,1,3,4,3]
k = 6
Output
1

Solution

This solution uses the Two Pointer technique. First, we sort the array so that the smallest element is at the beginning and the largest element is at the end.

We maintain two pointers: left starts at the beginning and right starts at the end. If nums[left] + nums[right] equals k, we have found a valid pair, so we increment the result and move both pointers inward.

If the sum is less than k, we move left forward to increase the sum. If the sum is greater than k, we move right backward to decrease the sum.

The process continues until the two pointers meet.
class Solution {
    public int maxOperations(int[] nums, int k) {
        Arrays.sort(nums);

        int left = 0;
        int right = nums.length - 1;
        int count = 0;

        while (left < right) {
            int sum = nums[left] + nums[right];

            if (sum == k) {
                count++;
                left++;
                right--;
            } else if (sum < k) {
                left++;
            } else {
                right--;
            }
        }
        return count;
    }
}

Complexity

Sorting the array takes O(n log n) time, and the two-pointer traversal takes O(n) time. Therefore, the overall time complexity is O(n log n).

The two-pointer traversal uses O(1) extra space apart from the space used internally by the sorting implementation.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion