-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
47 lines (41 loc) · 1.15 KB
/
index.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
const method = (unSortedArr, originalSum) => {
const results = [];
const sortedArr = unSortedArr.sort((a, b) => a-b);
let sum = originalSum;
let currentSum = 0;
let counter = sortedArr.length;
const push = (pointer) => {
results.push(sortedArr[pointer]);
currentSum = currentSum + sortedArr[pointer];
sum = sum - currentSum;
sortedArr.splice(pointer, 1);
counter = sortedArr.length;
};
while(currentSum !== originalSum && currentSum < originalSum && counter > 0) {
let l = 0, r = sortedArr.length - 1;
for (let i = 0; i < sortedArr.length; i++) {
if (sortedArr[l] + sortedArr[r] === sum) {
push(l);
push(r-1);
break;
}
else if(sortedArr[l] === sum || l === r) {
push(l);
break;
}
else if(sortedArr[r] === sum) {
push(r);
break;
}
else if (i === sortedArr.length - 1) {
push(l);
break;
}
sortedArr[l] + sortedArr[r] > sum && r--;
sortedArr[l] + sortedArr[r] < sum && l++;
}
counter--;
}
return results.reduce((a,b) => a + b, 0) === originalSum ? results : [];
};
module.exports = method;