Construct Target Array With Multiple Sums LeetCode solution in JavaScript

1
var isPossible = function (target) {
2
let max = 0;
3
let index = -1;
4

5
for (let i = target.length - 1; i >= 0; i--) {
6
if (target[i] > max) {
7
max = target[i];
8
index = i;
9
}
10
}
11
if (max === 1) return true; // if max itself is 1 return true
12

13
let total = 0;
14
for (let i = 0; i < target.length; i++) {
15
if (i !== index) {
16
total += target[i];
17
}
18
}
19
// If total=1,it means only one element was remaining apart from max and its value is 1 return true
20
// eg target=[10,1] we started with [1,1] so next steps would be [2,1]->[3,1]->...[10,1] we can make sure it leads to target
21
if (total === 1) return true;
22
// max should be greater than remaining nums sum OR if total is 0 it would lead to infinite loop( num%0 === NaN) so return false
23
if (max <= total || total === 0) return false;
24
max = max % total;
25
if (max < 1) return false; // it should not be less than 1
26
target[index] = max;
27

28
return isPossible(target);
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0