-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathTwoSumLessThanK.java
More file actions
32 lines (25 loc) · 883 Bytes
/
TwoSumLessThanK.java
File metadata and controls
32 lines (25 loc) · 883 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S
//and S < K. If no i, j exist satisfying this equation, return -1.
// Input: A = [34,23,1,24,75,33,54,8], K = 60
// Output: 58
// Explanation:
// We can use 34 and 24 to sum 58 which is less than 60.
//TC: O(nlogn)
//SC: O(1)
//1 sort the array;
class Solution {
public int twoSumLessThanK(int[] A, int K) {
Arrays.sort(A); // Time cost O(nlogn).
int max = -1;, i = 0, j = A.length - 1;
while (i < j) {
int sum = A[i] + A[j];
if (sum < K) { // find one candidate.
max = Math.max(max, sum);
++i; // increase the smaller element.
}else { // >= sum.
--j; // decrease the bigger element.
}
}
return max;
}
}