Dynamic Programming Patterns
Dynamic Programming (DP) is an optimization technique that solves complex problems by breaking them down into simpler subproblems.Core Concepts
Dynamic Programming is applicable when:
- Optimal Substructure: Optimal solution contains optimal solutions to subproblems
- Overlapping Subproblems: Same subproblems are solved multiple times
Knapsack Problems
0/1 Knapsack Problem
Given N items with weights and values, maximize value in a knapsack of capacity W. Each item can be used once.2D DP Approach
1D DP Approach (Space Optimized)
Complete Knapsack Problem
Each item can be used unlimited times.Knapsack Variations
Can Fill Knapsack?
Can Fill Knapsack?
Formula:
dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])Problems:- LeetCode 416: Partition Equal Subset Sum
- LeetCode 1049: Last Stone Weight II
Count Ways to Fill
Count Ways to Fill
Formula:
dp[j] += dp[j - nums[i]]Problems:- LeetCode 494: Target Sum
- LeetCode 518: Coin Change II
- LeetCode 377: Combination Sum IV
Maximum Value
Maximum Value
Formula:
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])Problems:- LeetCode 474: Ones and Zeroes
Minimum Items
Minimum Items
Formula:
dp[j] = min(dp[j], dp[j - coins[i]] + 1)Problems:- LeetCode 322: Coin Change
- LeetCode 279: Perfect Squares
Iteration Order
0/1 Knapsack Order
Complete Knapsack Order
Classic Problems
Problem 1: Partition Equal Subset Sum
LeetCode 416: Can partition array into two subsets with equal sum?Problem 2: Target Sum
LeetCode 494: Count ways to add +/- to nums to reach target.Mathematical Insight
Mathematical Insight
Let positive sum = P, negative sum = N:
- P + N = sum
- P - N = target
- Solving: P = (sum + target) / 2
Problem 3: Combination Sum IV (Permutations)
LeetCode 377: Count permutations that sum to target.Problem 4: Coin Change
LeetCode 322: Minimum coins needed to make amount.Stock Trading Problems
Problem 1: Best Time to Buy and Sell Stock
LeetCode 121: Buy and sell once for maximum profit.Problem 2: Best Time to Buy and Sell Stock II
LeetCode 122: Buy and sell multiple times.Problem 3: Best Time to Buy and Sell Stock III
LeetCode 123: At most 2 transactions.Problem 4: Best Time to Buy and Sell Stock with Cooldown
LeetCode 309: With 1-day cooldown after selling.DP Patterns Summary
Linear DP
Single sequence problems: Climbing Stairs, House Robber
Interval DP
Range problems: Burst Balloons, Palindrome Partitioning
Knapsack DP
Subset selection: Partition, Target Sum, Coin Change
State Machine DP
Multiple states: Stock Trading, Game Theory