Learn / Dynamic programming

Partition and interval DP

Interval DP uses the state (i, j): the best for the segment from i to j. Try every way to split it, often by choosing which element is handled last (the last matrix multiplication, the last balloon burst, the root of a search tree), and combine the two sides. Fill by increasing segment length; it is usually O(n³).

How to recognise it

  • A sequence where the order of combining or cutting matters.
  • Choosing a split point, a root, or the last element.
  • Two players taking from the ends.

Segments

for length in 2..n:
    for i, with j = i + length - 1:
        dp[i][j] = best over k of dp[i][k] + dp[k][j] + cost(i, k, j)
ProblemSplit by
matrix chain multiplicationthe last multiplication
burst balloonsthe last balloon burst
minimum cost to cut a stickthe first cut
optimal BSTthe root
boolean parenthesizationthe last operator (count true and false ways)
palindrome partitioning IIthe last palindromic piece (1D)
optimal game strategytake the left end or the right end

Common mistakes

  • Filling by i and j directly, so shorter segments are not ready.
  • Including the segment's endpoints in the cost when the problem excludes them (balloons, sticks).

Problems

0 of 9 solved

Check yourself

Why is 'which balloon bursts last?' a better choice than 'which bursts first?'

Matrix chain: what is tried for the segment of matrices i..j?

In what order are segments filled?

Egg dropping can be turned around to ask?