An airline ground crew is loading n numbered cargo crates, one at a time, and must pick exactly two distinct crates (two different positions in the lineup, even if their weights happen to be equal) to place together into a single overhead compartment. The compartment is rated to fail if the combined weight of the two crates placed in it is greater than or equal to a limit L, so the crew wants the combined weight to be as large as possible while staying strictly below L. Determine the largest achievable combined weight of two distinct crates that is strictly less than L, or report that no such pair exists.
n and L.n space-separated integers, the weight of each crate in order.Print a single integer: the maximum sum of the weights of two distinct crates that is strictly less than L. If every pair of crates has a combined weight of L or more, print -1 instead.
Example 1
Input
4 10 3 5 2 8
Expected
8
Explanation
The crate weights are [3,5,2,8] and the limit is 10. Pair sums are 3+5=8, 3+2=5, 3+8=11, 5+2=7, 5+8=13, 2+8=10. Only 8, 5, 7 and 10 are candidates to check against the strict limit; 10 is not strictly less than L=10 so it is excluded, leaving 8 as the largest valid sum.
Example 2
Input
3 3 5 6 7
Expected
-1
Explanation
The crate weights are [5,6,7] and the limit is 3. Every pair sum (11, 12, 13) is at least 3, so no pair has a combined weight strictly below the limit and the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →