1

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;
};
4
  • I don't understand the coding / algorithm challenge. What two arrays? What are L ad M? I think you left a lot of info out. Commented Apr 18, 2020 at 1:32
  • When you adding the previous value to current, it will give you the sum of subarray with length i+1. So later when you check subarray sum, if the subarray ending at index i, you know a subarray with length L has sum arr[i] - arr[i-L], so you don't need to iterate again from i-L to i to calculate sum. Commented Apr 18, 2020 at 1:37
  • @Inigo You're right, I mistakenly left out the link. Added. Commented Apr 18, 2020 at 1:57
  • hi, why is the for loop indexed from i = L+M? and can you please explain the for loop as well? Commented Jul 19, 2020 at 21:10

1 Answer 1

3

When you adding the previous value to current, it will give you sum of subarray with length i+1. So later when you check subarray sum, if the subarray ending at index i, you know a subarray with length L has sum arr[i] - arr[i-L], so you don't need to iterate again from i-L to i to calculate sum.

    0 arr[0]
    1 arr[0] + arr[1]
    2 arr[0] + arr[1] + arr[2]
    3 arr[0] + arr[1] + arr[2] + arr[3]
    ...

suppose L is length 2 then, later when you iterate array, you know arr[2] - arr[0] is the sum with length 2, same arr[3] - arr[1] is also the subarray sum with length 2. After doing this, you can calculate subarray sum with given length in O(1) time.

Without this step or any memorization, when you calculate non overlap subarray sum for length L and M, each time you will need to take O(L+M) time which is inefficient.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.