Overview
When computing the minimum of several linear functions `y = mx + c` evaluated at `x`, we only need to keep track of the lower envelope of these lines.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Optimize DP transitions of the form `dp[i] = min(dp[j] + m[j]*x[i] + c[j])` from O(N^2) to O(N) or O(N log N).
When computing the minimum of several linear functions `y = mx + c` evaluated at `x`, we only need to keep track of the lower envelope of these lines.
If line L2 is intersected by line L3 before L2 intersects L1, then L2 is "swallowed" by L1 and L3, meaning L2 is never the strict minimum at any `x`. It can be removed.
We maintain a stack of active lines (the hull). When adding a new line (sorted by slope), we pop lines from the end of the stack if they become redundant.
By discarding redundant lines, we drastically reduce the search space. We can then query the optimal line for any `x` using binary search or a monotonic pointer.