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 INPUT nums array: 34 23 1 24 75 33 54 8 i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 k = 60 Target threshold Find max sum where: nums[i] + nums[j] < k with i < j Length: 8 | Max: 75 | Min: 1 ALGORITHM STEPS 1 Sort Array [1,8,23,24,33,34,54,75] 2 Two Pointers left=0, right=7 3 Compare Sum sum < k? Update max 4 Move Pointers Adjust based on sum Key Iteration: L 24 + 34 = 58 <60 R 58 < 60 -- OK! Update max Complexity: Time: O(n log n) Space: O(1) FINAL RESULT Maximum Sum 58 Winning Pair: 24 + 34 Verification: 24 + 34 = 58 < 60 OK Original indices: i=3, j=0 (nums[3]=24, nums[0]=34) Next best: 57 (23+34) Key Insight: Sorting enables the two-pointer technique. When sum >= k, we need smaller values (move right pointer left). When sum < k, we found a valid pair - update max and try for larger sum (move left pointer right). This efficiently finds the maximum valid sum in O(n log n) time, dominated by the sorting step. TutorialsPoint - Two Sum Less Than K | Two Pointer Optimal Approach
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