Technique · CP 2400+
Slope Trick
Keep dp(x), a convex piecewise-linear function of a value x, as the multiset of its breakpoints in one or two heaps. Each transition (add |x - a|, take a prefix minimum, shift) then costs O(log n) heap operations instead of a pass over all values.
0/5 solved
Recognise it
The signal
make the array non-decreasing (or strictly increasing) with minimum total |change|
1Brute force
dp[i][v] over compressed values: O(n2) (the intended solution of CF 713C).
2The observation
Each step rewrites the whole function dp_i(.), but only O(1) breakpoints change.
3Why it works
dp_i is convex and piecewise linear. The left heap holds the breakpoints left of the minimum (the slope changes by 1 at each one), and the tracked minimum value is exact.
Reach for it when
- +cost is a sum of |x_i - a_i| terms under order constraints
- +dp over (index, value) where values go up to 1e9
- +buy/sell one unit per day, maximise profit
Not when
- ×the transition is not convexity-preserving
- ×you need the argmin sequence and skip the backward reconstruction pass
Practice
- Increasing Array IICSESMedium
- Sonya and Problem Wihtout a LegendCodeforces2300
- SequenceCodeforces2200
- Buy Low Sell HighCodeforces2400
- Make Array Non-decreasing or Non-increasingPremiumHard
Pitfalls
Misconceptions
- !for 'strictly increasing', subtract i from a_i first to reduce to non-decreasing
- !CF 865D can be read as slope trick or as regret greedy; they are the same heap at that size
Go deeper1 combinations · resources
Combinations
minimum total |change| to make an array non-decreasing, with large values
- Slope Trick:
- represent the cost function by its breakpoints
- Top-K Elements:
- a max-heap holds the breakpoints left of the minimum
Increasing Array IISonya and Problem Wihtout a LegendSequence