Two Sum Less Than K - Problem

Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k.

If no i, j exist satisfying this equation, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [34,23,1,24,75,33,54,8], k = 60
Output: 58
💡 Note: We can choose the pair (1, 54) or (24, 34) both giving sum 58, which is the maximum sum less than 60.
Example 2 — No Valid Pairs
$ Input: nums = [10,20,30], k = 15
Output: -1
💡 Note: The smallest possible sum is 10 + 20 = 30, which is not less than k = 15, so return -1.
Example 3 — Small Numbers
$ Input: nums = [1,2,3,4], k = 5
Output: 4
💡 Note: Choose pair (1, 3) with sum 4, which is the maximum sum less than k = 5.

Constraints

  • 2 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 1000
  • 1 ≤ k ≤ 2000

Visualization

Tap to expand
Two Sum Less Than K: Find Maximum Valid Pair SumInput Array:34231247533548k = 60Goal: Find pair with maximum sum < 60154+1 + 54 = 55 < 60 ✓Other valid pairs: (24,33)=57, (23,34)=57, (1,33)=34...Maximum Sum: 58(Pairs like 24+34=58 or 1+75=76≥60 invalid)
Understanding the Visualization
1
Input
Array [34,23,1,24,75,33,54,8] and k=60
2
Process
Find all pairs where sum < k, keep maximum
3
Output
Return 58 (maximum sum less than 60)
Key Takeaway
🎯 Key Insight: Sort first to enable efficient two-pointer technique for finding optimal pairs
Asked in
Amazon 15 Facebook 8 Google 12
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen