Two Sum Less Than K - Problem
Imagine you're at a casino with a limited budget! ๐ฐ Given an array nums of integers and an integer k, you need to find two different numbers whose sum is as close to k as possible, but strictly less than k.
Your task is to return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no such pair exists, return -1.
Example: If nums = [34,23,1,24,75,33,54,8] and k = 60, you want to find the pair that gives you the highest sum without going over 60. The answer would be 58 (from 34 + 24).
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [34,23,1,24,75,33,54,8], k = 60
โบ
Output:
58
๐ก Note:
We can choose the pair (34, 24) which gives us 34 + 24 = 58 < 60. This is the maximum possible sum less than 60.
example_2.py โ Small Array
$
Input:
nums = [10,20,30], k = 15
โบ
Output:
-1
๐ก Note:
No pair of numbers can sum to less than 15. The smallest possible sum is 10 + 20 = 30, which is โฅ 15.
example_3.py โ Edge Case
$
Input:
nums = [1,1,1,1], k = 3
โบ
Output:
2
๐ก Note:
Any pair of 1's will give us 1 + 1 = 2 < 3. Since all pairs have the same sum, we return 2.
Visualization
Tap to expand
Understanding the Visualization
1
Sort your chips by value
Arrange all chips from lowest to highest value for systematic selection
2
Use two-ended selection
Start with cheapest and most expensive chips available
3
Adjust selection intelligently
If total is under budget, try more expensive cheap chip. If over budget, try cheaper expensive chip
4
Track best combination
Remember the highest valid combination found during the process
Key Takeaway
๐ฏ Key Insight: Sorting enables intelligent navigation - when sum is too high, we need a smaller number (move right pointer left), when sum is too low, we need a larger number (move left pointer right). This systematic approach guarantees we find the optimal solution efficiently.
Time & Space Complexity
Time Complexity
O(n log n)
Sorting takes O(n log n), and the two-pointer traversal takes O(n)
โก Linearithmic
Space Complexity
O(1)
Only using constant extra space (if we sort in-place)
โ Linear Space
Constraints
- 1 โค nums.length โค 100
- 1 โค nums[i] โค 1000
- 1 โค k โค 2000
- Must find exactly two different elements (i < j)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code