Dynamic Programming21 sections · 916 units
Open in Course

CSES - DP Function Shape

Convexity preservation

dp[i]dp[i] as a function of vv (the value of aia_i) is convex and piecewise linear. Initially, dp[0](v)=va0dp[0](v) = |v - a_0|, a V-shape centered at a0a_0.

Adding vai|v - a_i| keeps convexity. The constraint "vprevious valuev \geq \text{previous value}" truncates the function on the left, preserving only the non-decreasing part. The minimum of dp[i]dp[i] is at the largest breakpoint less than or equal to the current choice. A max-heap tracks these breakpoints.