Dynamic Programming21 sections · 916 units
Open in Course

Loop Order

Why length matters

When you compute dp[i][j]dp[i][j], you need dp[i][k]dp[i][k] and dp[k+1][j]dp[k+1][j] for various k. Both of those are shorter ranges than [i,j][i,j].

So you must solve shorter ranges first. The outer loop iterates over length (from 11), and the inner loop iterates over starting positions. This is different from most DP where you iterate over indices directly. Getting the loop order wrong means you'll access uncomputed values.