DSA · Intermediate · Pattern 9 of 10
1-D Dynamic Programming
15 problems.
Your progress0%
- 1st Visit
- 0/15
- 2nd Visit
- 0/15
- Revise
- 0/15
About this pattern
Dynamic programming solves a problem by combining answers to overlapping subproblems, computing each one only once. In 1-D DP the state is a single index or value: dp[i] might be the best result for the first i elements, or for an amount i. Define the state in words, write the transition from smaller states, set the base cases, and pick an order in which every dependency is already computed.
Signals: a request for the number of ways, the minimum cost or the maximum value, where each step depends only on a few earlier results and plain recursion would repeat work. Typical complexity is O(n), or O(n * k) with k choices per state.
// dp[i] = best answer for a prefix of length i (or for amount i).
const long long INF = LLONG_MAX / 2;
vector<long long> dp(n + 1, INF);
dp[0] = 0; // base case
for (int i = 1; i <= n; ++i) {
for (int c : choices) { // transitions
if (i - c >= 0 && dp[i - c] != INF)
dp[i] = min(dp[i], dp[i - c] + cost(c));
}
}
// If dp[i] depends only on dp[i-1] and dp[i-2], keep two variables.