Dynamic programming
Динамическое программирование
This problem-solving technique breaks a task into smaller problems, saves their answers, and reuses those answers instead of doing the same work again.
Also known as: ДП, DP
When dynamic programming helps
Imagine finding the cheapest way to climb a staircase when you can move up one or two steps at a time. Many different routes pass through the same step. If all you need for the rest of the climb is your current position, there is no reason to reconsider every route that got you there: keep the cheapest cost of reaching that position. Dynamic programming (DP) uses this idea to avoid repeated work. It can also count solutions or answer yes/no questions, such as whether a target sum is reachable.
State, recurrence, and base cases
A state describes one subproblem. Give it a precise meaning before writing a formula: does dp[i] refer to the first i items, the item at index i, or something else? Include any information that changes the legal moves or their costs. For instance, in a budget problem, your position alone may not be enough; you may also need the remaining budget.
The recurrence explains how to compute a state's answer from other states. The base cases are the answers you know directly. You can evaluate the recurrence top-down with recursive calls and a cache (memoization), or bottom-up by filling in the answers in an order that makes each dependency available before it is read.
Example: count paths through a grid
Start in the top-left corner of an m-by-n grid with no obstacles, and move only right or down. There is one way to reach each cell in the top row or leftmost column. For any other cell, every path arrives from above or from the left. These two sets of paths are disjoint, so add their counts.
def count_paths(m, n): # m and n are positive
dp = [1] * n
for _ in range(1, m):
for c in range(1, n):
dp[c] += dp[c - 1]
return dp[-1]
The array holds one row's worth of counts. Just before the update, dp[c] still holds the count from above, while dp[c - 1] has already been updated to the count on the left. Iterating right to left would break that invariant. The code uses O(mn) arithmetic operations and O(n) storage slots; very large counts can make individual additions more expensive.
What interviewers look for
DP comes up in problems such as edit distance, knapsack, and scheduling jobs with different rewards. Walk through a small input and show why your recurrence covers every valid choice. For counting problems, also check that choices don't count the same solution twice. For optimization problems, don't assume the best immediate move leads to the best total: that's a greedy strategy, and it needs a separate correctness argument. Estimate the number of states and the work per state before optimizing memory.