Dynamic Programming21 sections · 916 units
Open in Course

Why O(n²) Total

The amortized analysis

For fixed length lenlen, you compute dp[i][j]dp[i][j] for all ii where j=i+len1j = i + len - 1. Each cell searches kk from opt[i][j1]opt[i][j-1] to opt[i+1][j]opt[i+1][j]. As ii increases, these ranges chain together: the right endpoint of one is the left endpoint of the next.

Example with n=5n=5, len=3len=3: cell (1,3)(1,3) searches [opt[1][2],opt[2][3]][opt[1][2], opt[2][3]]. Cell (2,4)(2,4) searches [opt[2][3],opt[3][4]][opt[2][3], opt[3][4]]. Cell (3,5)(3,5) searches [opt[3][4],opt[4][5]][opt[3][4], opt[4][5]]. The ranges tile [1,n][1, n] without overlap. Total kk checks per length: O(n)O(n). Summing over nn lengths: O(n2)O(n^2).