I was working on this algorithm in a leetcode challenge, and I found an interesting approach to the problem. Can anyone explain why, as the first step of this solution, we are adding the value of the previous item to the current?
Example input: [0,6,5,2,2,5,1,9,4], L = 1, M = 2.
Array after summing: [0, 6, 11, 13, 15, 20, 21, 30, 34]
Thanks in advance.
const maxSumTwoNoOverlap = (arr, L, M) => {
let len = arr.length;
for (let i = 1; i < len; i++) {
arr[i] += arr[i - 1];
}
let LMax = arr[L - 1], MMax = arr[M-1];
let res = arr[M + L - 1];
console.log('LMax', LMax);
console.log('MMax', MMax);
for (let i = M + L ; i< len ; i++) {
// update LMax to i - M;
LMax = Math.max(LMax, arr[i - M] - arr[i - M - L]);
MMax = Math.max(MMax, arr[i - L] - arr[i - M - L]);
res = Math.max(res,
LMax + arr[i] - arr[i - M],
MMax + arr[i] - arr[i - L]
)
}
return res;
};
LadM? I think you left a lot of info out.