# array leetcde

Can you please help me with this problem

Intuition

It is natural to consider an array W of each interval’s sum, where each interval is the given length k .
To create W , we can either use prefix sums, or manage the sum of the interval as a window slides along the array.

From there, we approach the reduced problem: Given some array W and an integer k , what is the lexicographically smallest tuple of indices (i, j, l) with i + l <= j and j + k <= l that maximizes W[i] + W[j] + W[l] ?

Algorithm

Suppose we fixed j .
We would like to know on the intervals i \in [0, j - k]i∈[0,j−k] and l \in [j + k, \text{len}(W) - 1]l∈[j+k,len(W)−1], where the largest value of W[i]W[i] (and respectively W[l]W[l]) occurs first.
(Here, first means the smaller index.)

We can solve these problems with dynamic programming.
For example, if we know that ii is where the largest value of W[i]W[i] occurs first on [0, 5][0,5], then on [0, 6][0,6] the first occurrence of the largest W[i]W[i] must be either ii or 66.
If say, 66 is better, then we set best = 6 .

At the end, left[z] will be the first occurrence of the largest value of W[i] on the interval i \in [0, z]i∈[0,z], and right[z] will be the same but on the interval i \in [z, \text{len}(W) - 1]i∈[z,len(W)−1]. This means that for some choice j , the candidate answer must be (left[j - k], j, right[j + k]) . We take the candidate that produces the maximum W[i] + W[j] + W[l] .

Other than dp,can there be any other approach to solve this

you can see this with linear time: