Best Pair Sum Below k
Problem
Choose two numbers from two different positions of the array so that their sum is as big as possible but strictly less than k. Print that sum, or -1 if no pair has a sum below k.
Constraints
- 1 <= n <= 10^5
- 1 <= a[i] <= 10^6
- 1 <= k <= 2 * 10^6
Examples
Input
8 34 23 1 24 75 33 54 8 60
Output
58
Solutions
After sorting, a sum below k means that the left number can still go up, so we move left. A sum that is too big needs a smaller right number. We look at O(n) pairs after the O(n log n) sort.
/*
* Problem : Best pair below k.
* Input : n, the array, then k.
* Output : The sum or -1.
* Approach: Sort and two pointers.
* Time : O(n log n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a, int k) {
// Step 1: Sort a copy. Then two pointers can walk from both ends.
int[] sorted = a.clone();
java.util.Arrays.sort(sorted);
int left = 0;
int right = sorted.length - 1;
int best = -1;
while (left < right) {
long sum = (long) sorted[left] + sorted[right];
// Step 2: A sum below k is a candidate. Move left to try a bigger sum. Otherwise move right to get a smaller sum.
if (sum < k) {
best = (int) Math.max(best, sum);
left++;
} else {
right--;
}
}
return best;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(solve(a, k));
}
}
Hints (2)
- Why can we skip many pairs?
- What do we do with a sum that is not below k?