-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClosestToZero.java
More file actions
43 lines (32 loc) · 1.19 KB
/
ClosestToZero.java
File metadata and controls
43 lines (32 loc) · 1.19 KB
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
33
34
35
36
37
38
39
40
41
42
43
// in the given list of integer, both +ve and -ve. Write a program to find the three elements such that their sum is closest to zero
package array.Questions;
import java.util.*;
public class ClosestToZero {
public static List<Integer> findClosestToZero(List<Integer> list) {
List<Integer> ClosestTrio = new ArrayList<>();
int closestSum = Integer.MAX_VALUE;
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
int start = 0;
int end = list.size() - 1;
while (start < end) {
int sum = list.get(start) + list.get(i) + list.get(end);
if (Math.abs(sum) < Math.abs(closestSum)) {
closestSum = sum;
if (!ClosestTrio.isEmpty()) {
ClosestTrio.clear();
}
ClosestTrio.add(list.get(start));
ClosestTrio.add(list.get(i));
ClosestTrio.add(list.get(end));
}
if (sum < 0) {
start++;
} else {
end--;
}
}
}
return ClosestTrio;
}
}