Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming/1D / Fibonacci-style

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.

Learn first1D / Fibonacci-styleTop-K Elements
0%
mastery
0/5 solved
Practise nextIncreasing Array II
IdeaPracticePitfalls

Recognise it

The signal

make the array non-decreasing (or strictly increasing) with minimum total |change|

  1. 1Brute force

    dp[i][v] over compressed values: O(n2) (the intended solution of CF 713C).

  2. 2The observation

    Each step rewrites the whole function dp_i(.), but only O(1) breakpoints change.

  3. 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

Next

Increasing Array II

0/5 solved
  • 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

  • Slope Trick+Top-K Elements

    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

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
TodayReviewPatternsProblems