Skip to content
CodeItRaw
Dynamic Programming

Lesson 3/4

Choosing what a box means is half the work. "The best answer among the first i elements" is often not enough to work out the next box; "the best answer that ends exactly at i" is. For the largest sum of a contiguous run the question is: does the best run ending at i extend the one before, or start afresh at i?

here = best = values[0]
for v in values[1:]:
here = max(v, here + v)
best = max(best, here)
return best
here is the best total that ends exactly at this element: once the earlier total has gone negative there is no point carrying it, so you start again. The real answer is the largest of all the here values, not the last one.

Counting follows the same pattern. Counting how many ways a string of digits can be read as letters, the box becomes "how many readings the first i digits have"; if the last digit is a letter on its own the box before is added, and if the last two digits together are a letter the box two before is added.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Maximum Subarray

    Function

  2. 02

    Decode Ways

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list