Convex Hull Trick & Li Chao Segment Trees: Optimizing Linear Cost DP from O(N^2) to O(N log N)

When a dynamic programming recurrence has the form $dp[i] = min_{j < i} (dp[j] + m_j cdot x_i + c_j)$, each candidate $j$ represents a linear equation $y = m_j x + k_j$. The Convex Hull Trick maintains the lower envelope of these lines to query optimal values in $O(log N)$ or amortized $O(1)$ time.

1. Monotonic Slope Deque Optimization

If slopes $m_j$ and query coordinates $x_i$ are monotonically ordered, we can maintain the convex hull lines in a double-ended queue, pruning suboptimal lines from the back when their intersection point with previous lines is dominated.

Ready to Master LeetCode Hard Patterns?

Get instant lifetime access to all 45 video lectures, interactive source code templates, and interview prep guides.

Enroll in Masterclass ($49)

Disclaimer: LeetCode is a registered trademark of LeetCode LLC. Our tutorials are independent educational guides developed by industry veterans and are not affiliated with LeetCode.