tests = [
[
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
], 45
],
[
[
[-1, -2, -3],
[4, 5, 6],
[-7, -8, -9]
], 15
],
[
[
[-1, -2, -3],
[-4, 5, -6],
[-7, -8, -9]
], 5
],
[
[
[0, -2, -7, 0],
[9, 2, -6, 2],
[-4, 1, -4, 1],
[-1, 8, 0, -2]
], 15
],
[
[
[0, 9, -4, -1, 6, -5],
[-2, 2, 1, 8, 3, 7],
[-7, -6, -4, 0, -8, 11],
[0, 2, 1, -2, -5, 6]
], 26
]
]
function maxSumOf(arr) {
let [n, m] = [arr.length, arr[0].length];
let tbl = [
[...Array(m).keys()].fill(0)
].concat(arr);
for (let i = 1; i <= n; i++) {
for (let j = 0; j < m; j++) {
tbl[i][j] += tbl[i - 1][j]
}
}
let max = tbl[1][0];
for (let k = 1; k <= n; k++) {
for (let i = 0; i <= n - k; i++) {
let t = 0;
for (let j = 0; j < m; j++) {
if (t >= 0) {
t += tbl[i + k][j] - tbl[i][j];
} else {
t = tbl[i + k][j] - tbl[i][j];
}
if (t > max) max = t;
}
}
}
return max;
}
for (let [arr, out] of tests) {
let r = maxSumOf(arr);
console.log(r, out);
}
To embed this program on your website, copy the following code and paste it into your website's HTML: