Dynamic Programming21 sections · 916 units
Open in Course

Intro

The Goal

Your DP (dynamic programming) recurrence (the formula relating states, introduced in Section 1) looks like dp[i]=minj(dp[j]+ajbi+cj)dp[i] = \min_j(dp[j] + a_j \cdot b_i + c_j). For each ii, you check all jj. That's O(n2)O(n^2).

But notice something: the expression ajbi+cja_j \cdot b_i + c_j is linear in bib_i. Each jj defines a line. You're finding the minimum among nn lines at point bib_i. Most of those lines will never be optimal. I'll teach you to keep only the useful ones. By the end, you'll reduce O(n2)O(n^2) to O(n)O(n) using the Convex Hull Trick (I'll explain why it's called "convex" in Unit 5).