Skip to content

Commit 49114cc

Browse files
authored
Create 1020-partition-array-into-three-parts-with-equal-sum.js
1 parent d916942 commit 49114cc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} A
3+
* @return {boolean}
4+
*/
5+
const canThreePartsEqualSum = function(A) {
6+
let lo = 0
7+
let hi = A.length - 1
8+
let lsum = 0
9+
let hsum = 0
10+
const sum = A.reduce((ac, el) => ac + el, 0)
11+
if(sum % 3 !== 0) return false
12+
const target = sum / 3
13+
14+
while(lo < hi && lsum !== target) {
15+
lsum += A[lo]
16+
lo++
17+
}
18+
if(lsum !== target) return false
19+
while(lo < hi && hsum !== target) {
20+
hsum += A[hi]
21+
hi--
22+
}
23+
if(hsum !== target) return false
24+
25+
let msum = 0
26+
for(let i = lo; i <= hi; i++) {
27+
msum += A[i]
28+
}
29+
if(msum !== target) return false
30+
return true
31+
};

0 commit comments

Comments
 (0)