-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSliceSum.js
More file actions
28 lines (21 loc) · 779 Bytes
/
MaxSliceSum.js
File metadata and controls
28 lines (21 loc) · 779 Bytes
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
//Score: 100%
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
var maxToTheLeft = new Array(A.length);
maxToTheLeft[0] = A[0];
for(var i = 1; i < A.length; i++){
maxToTheLeft[i] = Math.max(maxToTheLeft[i-1]+A[i], A[i]);
}
var maxToTheRight = new Array(A.length);
maxToTheRight[A.length - 1] = A[A.length - 1];
for(var i = A.length -2; i >= 0; i--){
maxToTheRight[i] = Math.max(maxToTheRight[i+1]+A[i], A[i]);
}
var max = -Infinity;
for(var i = 0; i < A.length; i++){
max = Math.max(max, maxToTheLeft[i] - A[i] + maxToTheRight[i]);
}
return max;
}