PrepStack · Markdown HTML

Linear dynamic programming

Dynamic programming · HTML

Formal shape

dp[i] denotes an optimum/count for the first i items or a solution ending at i. A transition dp[i]=Aggregate(dp[j],local(j,i)) ranges over a finite neighborhood or all j<i, with explicit empty-prefix or first-item bases.

Recognition signals

False friends

SignalWhy it is different
A provably exchangeable local choiceIf one choice never causes regret, greedy is simpler; DP is for historical branches that must coexist.
Future behavior depends on a chosen setAn index alone is insufficient when the selected subset matters; use a bitmask or richer state.
A fixed-window statisticWithout decision overlap, a sliding window or prefix aggregate is the more direct model.

Core invariant

After processing i, every state through i equals the true value under its definition, and every future transition reads only these finalized states.

State, transition, and processing order

ItemDefinition
StateA prefix/position plus the minimal summary the future needs; optionally a parent link for reconstruction.
TransitionEnumerate every possible previous state of the last step, combine its answer with the local contribution, then aggregate by min, max, sum, or logical OR.
Frontier / orderThe next index in dependency topological order, normally left to right; fixed-width dependencies permit rolling storage.

Python skeleton

def min_linear_cost(cost):
    n = len(cost)
    if n == 0: return 0
    if n == 1: return cost[0]
    prev2, prev1 = cost[0], cost[1]
    for i in range(2, n):
        cur = cost[i] + min(prev1, prev2)
        prev2, prev1 = prev1, cur
    return min(prev1, prev2)

Correctness sketch

  1. Base states directly cover the smallest domains.
  2. Assume prior states meet their definitions; every complete solution reaching i has one last predecessor included by the transition.
  3. Aggregating this complete set of correct candidates yields the correct state i, and induction reaches the answer.

Complexity

TimeSpaceParameters
O(n·d), where d is predecessors checked per state; O(n) for fixed dO(n), compressible to O(d) for fixed dependencen is sequence length and d transition indegree.

Edge cases

Error patterns

PatternWhy it fails / fix
Writing a recurrence before defining state‘First i items’ and ‘ending at i’ produce different indices, bases, and answers.
Overwriting a needed predecessorDraw dependencies before rolling compression and preserve every old value required by the update.
A base case fitted to examplesInitialization must follow the state definition, not convenient sample values.
Returning only the last cellSome processes may end in several tail states that require a final aggregate.

Selection and exclusion rules

RelationTemplateBoundary
optimizationMonotonic deque for window extremaA transition takes an extreme over a sliding predecessor range.
DAG-order compositionTopological sort / indegree eliminationWhen DP states form a general DAG, topological order supplies a valid evaluation order; ordinary linear DP does not require topological sort as a prerequisite.

Original micro-example

PartDetail
ResultThe minimum is min(1,7)=1, illustrating that the answer need not be the last state.
SetupSegment costs are [4,1,6]; start on either of the first two segments, move one or two segments, and finish by stepping beyond the end.
TraceCost to land on segment three is 6+min(4,1)=7; exit may follow segment two or three.

Recall prompts

My notes