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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code