Dynamic Programming21 sections · 916 units
Open in Course

When Naive DP Fails

The problem

Consider dp[i]=minj<i(dp[j]+cost(j,i))dp[i] = \min_{j < i}(dp[j] + cost(j, i)). For each of nn states, you check O(n)O(n) previous states. That's O(n2)O(n^2). For interval DP like dp[i][j]=mink(dp[i][k]+dp[k+1][j])+cost(i,j)dp[i][j] = \min_k(dp[i][k] + dp[k+1][j]) + cost(i,j), you have O(n2)O(n^2) states and O(n)O(n) choices per state. That's O(n3)O(n^3).

With n=105n = 10^5 or even n=4000n = 4000, these are too slow. But what if you didn't need to check every jj or every kk?