Get consecutive sequence of size 3 from list of numbers that has maximum sum 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!
 A: 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



A: Suppose you want to find the consecutive sequence of length $L$ with maximum sum from the list $[x_1, x_2, \dots, x_n]$. You have to do some form of iteration through the list: at the very least, a correct algorithm will read every entry, so it's impossible to do better than linear time.
However, you don't need to compute the sum of the consecutive numbers from scratch each time. Start by computing the sum $S_1$ in range $[1, L]$. You can then quickly compute the remaining sums from the previous sum: if you know the sum $S_{i}$ of the elements $x_{i}, \dots, x_{i + L - 1}$, you can compute $S_{i + 1}$ as $S_i - x_i + x_{i + L}$. Keeping track of the maximum $S_i$ gives you your answer. This will run in linear time in $n$ independent of $L$.
