Skip to content

DP Cheatsheet

Use this page when the state is close, but you still need to stabilize what each transition is allowed to remember.

Do Not Use When

  • the problem is already greedy after sorting or scanning
  • the real blocker is a missing graph / number-theory observation
  • you still cannot say what the state forgets and what it must preserve

Choose By Signal

State Checklist

  • what has been processed?
  • what still matters?
  • does the state forget any information needed later?

Transition Checklist

  • are all legal next moves covered?
  • are any cases counted twice?
  • what iteration order respects dependencies?

Common Forms

dp[i] = best answer on the first i elements
dp[i][j] = answer on prefix i with extra parameter j

Retrieval Cues

Core Invariant

The state must remember exactly the information needed for future decisions, and nothing more.

If two histories are indistinguishable for all future transitions, they should collapse into the same state.

Window-Flavored DP

Useful snippets when a DP or greedy transition needs the best value over a recent window:

Repo anchor:

Safety Checks

  • base case
  • final answer location
  • overflow type
  • reconstruction needs parent or choice arrays

Main Trap

The classic DP bug is not syntax. It is a state that silently throws away information the future still needs, or an iteration order that reads values before they are ready.

Reopen Paths