Core DP Concepts
State Definition Patterns
-
Linear State (1D DP)
- Index-based states: dp[i] represents optimal value up to index i
- Value-based states: dp[val] represents optimal way to achieve value val
-
Matrix State (2D DP)
- Grid-based states: dp[i][j] represents optimal value at position (i,j)
- Two-sequence states: dp[i][j] represents optimal value using first i and j elements
-
State with Constraints
- Limited resource states: dp[i][k] represents optimal value up to i using k resources
- Boolean states: dp[i][true/false] represents optimal value with condition met/not met
Coin-Based Problems
- Minimum Coins Problem
Key Insights:
- State Definition: dp[x] = minimum coins needed for amount x
- Base Case: dp[0] = 0 (no coins needed for zero amount)
- Transition: Consider each coin for each amount
- Time Complexity: O(amount * len(coins))
- Space Complexity: O(amount)
- Coin Combinations Problem
Key Insights:
- State Definition: dp[x] = number of ways to make amount x
- Base Case: dp[0] = 1 (one way to make zero amount)
- Order of loops matters:
- Outer coin loop → combinations (order doesn’t matter)
- Outer amount loop → permutations (order matters)
- Coin Path Reconstruction
Key Insights:
- Additional array needed to track choices
- Path reconstruction works backwards
- Time and space complexity remain the same
Minimum Value Problems
- Linear Minimum Cost Template
Key Insights:
- Used for problems with linear progression
- Consider all possible moves from each state
- Initialize with infinity except base case