Command Palette

Search for a command to run...

Module 32

Advanced DP

State machines for stock trading, interval DP for bursting and cutting, DP on trees, and bitmask DP over subsets.

Advanced 4 lessons 9 problems ~50 min of lessons

Once 1D, grid, knapsack and sequence DP feel natural, the remaining DP problems mostly differ in what the state looks like. A state machine adds "which mode am I in" to each day. Interval DP solves every range [i, j] by choosing the last (or first) split. Tree DP returns a small tuple from each subtree. Bitmask DP uses an integer to remember which of up to ~20 items are used.

This module teaches each of those four shapes with a lesson and problems, so that a new hard DP problem becomes a matter of choosing the right state.

Best after: DP on Strings and Sequences

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. A three-state machine updated daily.

  2. Two states, with the fee paid on each sale.

  3. A transaction counter in the state: k (buy, sell) pairs.

  4. Interval DP with the "last one to burst" choice.

  5. Interval DP over cut positions: each cut costs the current segment's length.

  6. Tree DP returning (rob, skip) from every subtree.

  7. Three states per node; the bottom-up rule places cameras on the parents of leaves.

  8. dp[mask] = filled amount of the current bucket after using the items in mask.

  9. BFS over (node, visited-mask) states: a bitmask in a graph search.