Get consecutive sequence of size 3 from list of numbers that has maximum sum

algorithms

I have a list of unsorted integers (>=0)
{2,10,5,3,5,2,4}.
and I want to get consecutive sequence of size 3 from the list that has the maximum sum.
Given the example, it should be {10,5,3}

Is iterating through the list the only way to achieve this?


Another question is, if I not only want to get sequence of size 3, but also of other sizes, is there a way so that I don't need to iterate through the list every time?

Thanks!

Best Answer

You can accomplish this task using the cumulative sums of your list items.

Let $a_i$ be the items of list $A$, with $0\le i<N$, where $N$ is the length of the list. Then the sequence $S$ of cumulative sums is defined as $$s_0=0$$ $$s_i = \sum_{j=0}^{j=i-1} a_j$$

The sum of the subsequence of length $L$ starting at $i$ is simply $$s_{i+L} - s_{i}$$

So once you've computed $S$ you can easily find the sums of the subsequences of any length. (And of course finding the maximum is a simple linear operation).

In software, you can easily compute $S$ with a simple for loop, but your language may also provide a library function for cumulative sums. Eg, Python has accumulate.

Here's your list and its cumulative sums.

List 2 10 5 3 5 2 4
Sums 0 2 12 17 20 25 27 31

Here we find the sums of the subsequences of length 3 by subtracting the items of $S$ from the items of $S$ shifted by 3 places.

Shifted 17 20 25 27 31
Sums 0 2 12 17 20
Diff 17 18 13 10 11
Related Question