-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclosestThreeSum.java
More file actions
31 lines (25 loc) · 943 Bytes
/
closestThreeSum.java
File metadata and controls
31 lines (25 loc) · 943 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
import java.util.Arrays;
class Solution {
static int threeSumClosest(int[] array, int target) {
Arrays.sort(array);
int n = array.length;
int closestSum = Integer.MIN_VALUE;
for (int i = 0; i < n - 2; i++) {
int left = i + 1;
int right = n - 1;
while (left < right) {
int currentSum = array[i] + array[left] + array[right];
if (Math.abs(currentSum - target) < Math.abs(closestSum - target) ||
(Math.abs(currentSum - target) == Math.abs(closestSum - target) && currentSum > closestSum)) {
closestSum = currentSum;
}
if (currentSum < target) {
left++;
} else {
right--;
}
}
}
return closestSum;
}
}