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/State Machine DP (Stocks)

Technique

Convex Hull Trick / Li Chao Tree

When dp[i] = min_j (m_j * x_i + b_j), keep lines on a lower envelope (monotone deque or Li Chao tree) and query min at x_i in O(1)/O(log n).

Learn first1D / Fibonacci-styleComputational Geometry PrimitivesMonotonic Deque
0%
mastery
0/7 solved
Practise nextMonster Game I
IdeaPracticePitfalls

Recognise it

The signal

transition cost is a product of a j-term and an i-term

  1. 1Brute force

    Try every j for every i.

  2. 2The observation

    Scanning all previous j: only lines on the envelope can be optimal.

  3. 3Why it works

    The structure stores exactly the lines that are minimal at some x.

Reach for it when

  • +slopes or queries monotone (deque CHT) or arbitrary (Li Chao)

Not when

  • ×cost is not separable into m_j x_i + b_j

Practice

Next

Monster Game I

0/7 solved
  • Monster Game ICSESHard
  • Monster Game IICSESHard
  • The Fair Nut and RectanglesCodeforces2400
  • Lines and Queries ICSESHard
  • Lines and Queries IICSESHard
  • Line Segments Trace ICSESHard
  • Line Segments Trace IICSESHard

Pitfalls

Misconceptions

  • !overflow in intersection comparisons (use __int128 or cross-multiply carefully)
Go deeper1 combinations · resources

Combinations

  • Convex Hull Trick / Li Chao Tree+1D / Fibonacci-style

    cost is product of a term of j and a term of i

    Convex Hull Trick / Li Chao Tree:
    queries the lower envelope of lines
    1D / Fibonacci-style:
    defines dp[i] = min_j (m_j * x_i + b_j) + c_i

    Monster Game IMonster Game IIThe Fair Nut and Rectangles

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