Problem 374
Two Sum Less Than K
Easy · 10 pts · Array, Two Pointers, Sorting
Problem
Find the largest possible sum A[i] + A[j] over two different positions i < j such that the sum is strictly less than K. If no pair has a sum below K, print -1. Sorting the array and moving two pointers inward finds the answer in O(N log N): when the sum is too large, move the right pointer left; otherwise record it and move the left pointer right.
Input
First line: N and K. Second line: N integers.
Output
Print the largest pair sum below K, or -1.
Constraints
1 <= N <= 100000; 1 <= A[i] <= 1000; 1 <= K <= 2000
Example input
8 60 34 23 1 24 75 33 54 8
Example output
58
Explanation
With K = 60 in 34 23 1 24 75 33 54 8, the pair 34 + 24 = 58 is the largest sum that stays below 60.