-
Notifications
You must be signed in to change notification settings - Fork 0
/
15.4 MinAbsSumOfTwo.js
50 lines (40 loc) · 1.01 KB
/
15.4 MinAbsSumOfTwo.js
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
44
45
46
47
48
49
50
function solution(A) {
if (A.length === 1) {
return Math.abs(A[0] + A[0]);
}
A = A.sort((a,b) => {
return a-b;
});
if (A[A.length-1] <= 0){
return Math.abs(A[A.length - 1] + A[A.length - 1]);
}
let startIndex = 0;
let endIndex = A.length - 1;
let min = Math.abs(A[endIndex] + A[startIndex]);
while (startIndex < endIndex){
const minValue = A[startIndex];
const maxValue = A[endIndex];
if (minValue === -1 * maxValue){
return 0;
}
if (minValue >= 0){
let potentialMin = Math.abs(minValue + minValue);
min = Math.min(min, potentialMin);
break;
}
if (maxValue <= 0){
break;
}
if (minValue <= 0 && maxValue >= 0){
let potentialMin = Math.abs(minValue + maxValue);
min = Math.min(min, potentialMin);
if (Math.abs(minValue) > maxValue) {
startIndex ++;
} else if (maxValue > Math.abs(minValue)) {
endIndex --;
}
continue;
}
}
return min;
}