Two Sum Less Than K

Sort and two-pointer for the maximum pair sum strictly less than k.

Easy
Time O(n log n) Space O(1)
LeetCode
3 min read
two-pointers sorting

Problem#

Given an array nums and integer k, return the maximum sum nums[i] + nums[j] with i != j and the sum strictly less than k. Return -1 if no pair qualifies.

Examples#

  • nums = [34,23,1,24,75,33,54,8], k = 6058 (34 + 24)
  • nums = [10,20,30], k = 15-1

Constraints#

  • 1 <= nums.length <= 100, 1 <= nums[i] <= 1000, 1 <= k <= 2000.

Approach#

Sort. Use two pointers from both ends: if the sum is below k, record and move the left pointer up; otherwise move the right pointer down.

Solution#

Two Sum Less Than K
class Solution {
public:
int twoSumLessThanK(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int l = 0, r = nums.size() - 1, best = -1;
while (l < r) {
int s = nums[l] + nums[r];
if (s < k) {
best = max(best, s);
++l;
} else {
--r;
}
}
return best;
}
};

Editorial#

After sorting, two pointers explore the Pareto frontier of pair sums in O(n). When s < k, increasing l is the only way to potentially raise the sum while staying valid; when s >= k, decreasing r is the only way to shrink it.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.