JSFiddle - React, Tailwind, and code Playground
by krustnic
HTML
<div id="root" class="root">
<div id="child1">
<div id="child2">child2</div>
</div>
<div id="child3">child3</div>
</div>
JavaScript
function maxContiguousSum(arr) {
let cache = []
let max = -Infinity
for(let i=0; i<arr.length; i++) {
const s = (cache[i-1] || 0) + arr[i]
cache.push(s)
}
console.log(cache)
for(let i=1; i<arr.length - 1; i++) {
const newCache = []
for(let j=i + 1; j<arr.length; j++) {
if (cache[j-i]) {
s = cache[j-i] - arr[i-1]
} else {
s += arr[j]
}
if (max < s && s >= 0) {
max = s
}
newCache.push(s)
}
cache = newCache
console.log(cache)
}
return max === -Infinity ? 0 : max
}
function maxContiguousSum2 (arr) {
let cache = []
let max = -Infinity
for(let i=0; i<arr.length - 1; i++) {
let s = arr[i]
if (max < arr[i] && arr[i] >= 0) {
max = arr[i]
}
const newCache = []
for(let j=i + 1; j<arr.length; j++) {
if (cache[j-i]) {
s = cache[j-i] - arr[i-1]
} else {
console.log("no value")
s += arr[j]
cache.push(s)
}
if (max < s && s >= 0) {
max = s
}
newCache.push(s)
}
cache = newCache
console.log(cache)
}
return max === -Infinity ? 0 : max
}
// console.log(maxContiguousSum([3, -4, 8, 7, -10, 19, -3]))
console.log(maxContiguousSum([2, -3, -3, 9, -29, 8, -9]))
// console.log(maxContiguousSum([1, 1, 1, 1, 1]))