// https://[Log in to view URL]
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
function maxSum(arr) {
let maxCurrent = arr[0], maxGlobal = arr[0];
for (let i = 1; i < arr.length; i++) {
maxCurrent = Math.max(arr[i], (maxCurrent + arr[i]))
if (maxCurrent > maxGlobal) {
maxGlobal = maxCurrent
}
}
return maxGlobal
}
console.log(maxSum(arr))
// 1st loop
// maxCurrent = (1, (-2+1)).max = 1
// if maxCurrent(1) > maxGlobal(-2)
// maxGlobal(-2) = maxCurrent(1)
// maxGlobal(1)
// maxCurrent(1)
// 2nd looop
// maxCurrent(1) = (-3, (1 + -3)).max = -2
// maxCurrent(-2)
// if maxCurrent(-2) > maxGlobal(1)
// false
// maxCurrent(-2)
// maxGlobal(1)
// 3rd loop
// maxCurrent(-2) = (4, (-2 + 4)).max = 4
// if maxCurrent(4) > maxGlobal(1)
// maxGlobal(1) = maxCurrent(4)
// maxGlobal(4)
// maxCurrent(4)
To embed this project on your website, copy the following code and paste it into your website's HTML: