Statementâ–¼
Given an array of integers, nums
, and an integer k
, find the maximum sum of two elements in nums
less than k
. Otherwise, return
Constraints:
1≤ nums.length
≤100 1≤ nums[i]
≤103 1≤ k
≤103
Solution
This solution uses the following approaches to find the maximum of the two values, which is less than k
.
Sorting: The array is first sorted in ascending order to facilitate the binary search and avoid checking every possible pair.
Binary Search: For each number in the sorted array, a binary search is performed to find the largest number after the given index such that the sum of the two numbers is less than
k
. This narrows the search space, reducing the time complexity compared to brute force.Tracking Maximum: As the solution iterates through the array and finds two numbers whose sum is less than
k
, the result is updated with the maximum sum that meets the condition.
Here’s the step-by-step implementation of the solution:
Initialize a variable
maximum_sum
to store the maximum sum.Sort the
nums
to help binary search find two numbers whose sum is less thank
, without searching through the whole array.Iterate through
nums
, and for eachnums[i]
:Calculate the target
k - nums[i]
.Call the
search
function to find the largest indexj > i
such thatnums[i] + nums[j]
is less thank
.If two numbers are found (i.e.,
j > i
), update themaximum_sum
with the maximum sum found so far.
Return the
maximum_sum
which represents the maximum sum, if there is any. Otherwise,−1 is returned.
The helper function search
 uses binary search to find the index j
such that the sum nums[i]+nums[j] < k
. It takes the nums
 array, target
value, and the start
 range of the search as input and performs the following steps:
Initialize
left
tostart
andright
to the last index in thenums
.Initialize
result
to store the indexj
.Perform binary search until
left
exceedsright
:Calculate the midpoint,Â
mid
, betweenÂleft
 andÂright
.If
nums[mid] < target
, updateresult
tomid
and moveleft
tomid + 1
to look for larger values.If
nums[mid] >= target,
moveright
tomid - 1
to check smaller values.
Return
result
which represents the indexj
such thatnums[j] < target
.
Let’s look at the following illustration to get a better understanding of the solution: