Loading content...
You are given an array of positive integers nums and an integer threshold.
Your task is to find two distinct elements from the array (at indices i and j where i < j) such that their sum is strictly less than the threshold, and this sum is the maximum possible among all such valid pairs.
Return the maximum sum that satisfies these conditions. If no such pair exists where the sum is strictly less than the threshold, return -1.
Key Observations:
nums = [34,23,1,24,75,33,54,8]
threshold = 6058We can choose the elements 34 and 24. Their sum is 34 + 24 = 58, which is strictly less than 60. No other valid pair produces a larger sum below the threshold. For instance, 34 + 33 = 67 exceeds the threshold, so it's invalid.
nums = [10,20,30]
threshold = 15-1The smallest possible pair sum is 10 + 20 = 30, which is not less than 15. Even the minimum pair exceeds the threshold, so no valid pair exists. We return -1.
nums = [5,8,3,2,10]
threshold = 1211The pair (5, 3) produces sum 8, and the pair (8, 3) produces sum 11. Since 11 < 12 and is the maximum valid sum, we return 11. Note that 8 + 5 = 13 exceeds the threshold and is invalid.
Constraints