Update window state on include
Updated
On include, fold a[R] into the window state: sum += a[R]. Do it when R moves, not by rescanning a[L..R].
What to focus on
After include, state equals the aggregate of a[L..R]. Constraint here is running sum. One add per expand.
Worked examples
add first
a = [4, 1, 9], L=0 R=0, state=0- include a[0]=4
- state += 4
Result: state = 4
add second
a = [4, 1, 9], L=0 R=1, state=4- include a[1]=1
- state += 1
Result: state = 5
add third
a = [4, 1, 9, 1], L=0 R=2, state=5- include a[2]=9
- state += 9
Result: state = 14
Try it
Write includeSum(a, state). a is an array of integers. state is the running sum of a[L..R] before the new cell. R is the newly included in-range index. The window includes a[R] after the add. Do state += a[R] after R += 1. Return the new state. On [4, 1, 9] expanding to R=0 then R=1; [4, 1, 9, 1] then R=2.
a is nonempty. All values are integers. R is the newly included in-range index.