Problem Description
Given an array of integers nums and an integer k, return the maximum sum of any two distinct numbers in nums such that their sum is less than k. If no valid pair exists, return -1.
Key Insights
- Sorting the array simplifies pair selection by ordering the values.
- A two-pointer approach can efficiently explore potential pairs.
- Adjust the two pointers based on whether the current pair sum is less than k.
- Ensure that the best candidate is continuously updated with valid sums.
Space and Time Complexity
Time Complexity: O(n log n) due to the sort operation, and O(n) for the two-pointer scan, resulting in an overall O(n log n). Space Complexity: O(1) if sorting in-place; otherwise, O(n) if a separate sorted copy is used.
Solution
The solution sorts the array and then employs a two-pointer technique. Start with one pointer at the beginning and one at the end of the array. At each step:
- Calculate the sum of the values at the two pointers.
- If the sum is less than k, update the maximum sum and move the left pointer rightwards to try for a larger sum.
- If the sum is greater than or equal to k, move the right pointer leftwards to reduce the sum. Continue until the pointers meet, and finally return the best valid sum found, or -1 if no valid pair exists.