Arrays and strings · Exercise 15 of 100

Maximum Subarray Sum

A nonempty subarray uses one or more neighboring values without skipping any. Start with the first value, then at each new value choose the larger sum from starting fresh there or extending the best sum ending at the previous slot. Keep the largest sum you see because the best subarray can end before the array does.

Try it yourself

A shop's daily gains and losses are [4, -6, 5, -2, 6, -7]. What is the greatest total over any nonempty run of consecutive days?

One-step hint

For each day, compare starting a run that day with extending the best run ending yesterday. Keep the largest total you see.

Worked solution
  1. The first two ending sums are 4 and -2. On day three, start fresh at 5 because extending -2 would give only 3.
  2. The next ending sums are 3, 9 and 2. The largest is 9, from the consecutive days with gains and losses of 5, -2 and 6.
DSA compiler