Python 3D Academyবাংলা

Dynamic Programming Patterns in Python

Chapter 59: Dynamic Programming Patterns

7 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Longest increasing subsequence

    Let dp[i] be the length of the longest increasing run that ends with nums[i]; the number before nums[i] in that run is some earlier, smaller nums[j], so dp[i] is 1 more than the best such dp[j], and the answer is the largest cell.

  2. Partition and subset sum

    Subset sum asks whether some of the numbers add up to exactly a target; dp[i][s] is True when the first i numbers can make s, either without number i (dp[i − 1][s]) or with it (dp[i − 1][s − x]), which is the 0/1 knapsack of Lesson 58.3 with True and False instead of values.

  3. DP on strings: palindromes

    Let pal[i][j] say whether the piece s[i..j] is a palindrome: it is when its two end letters match and the piece between them is one, so fill the table from short pieces to long, and every piece finds its inside already decided.

  4. Saving memory, and rebuilding the actual answer

    When every row reads only the row above, keep just two rows (or even one) and the memory drops from the whole table to one row; to rebuild the actual answer, keep the full table or, for each cell, which earlier cell its value came from, and walk those links back from the answer.

  5. State machines: stocks with a cooldown

    Keep, for each day, the best money you could have in each state, holding a lot, having just sold, or resting with no lot, and work out today's three numbers from yesterday's through the moves allowed between states.

  6. DP on trees: each node passes up two answers

    For each node, work out two best values, one if the node is taken and one if it isn't, using only its children's pairs, and the root's better value is the answer.

  7. Interval DP: bursting balloons and cutting sticks

    dp[l][r] is the best answer for the items strictly between positions l and r; try every item k as the one that splits the range (for balloons: the last one burst, whose neighbours are then l and r), and fill the table from short ranges to long ones.