Dynamic Programming (DP) is a method used in programming to solve complex problems by breaking them down into simpler
subproblems. It is particularly useful when the problem can be divided into overlapping subproblems with optimal
substructure.
Dynamic Programming is an optimization technique that:
It’s widely used in problems like:
Without DP, you may solve the same subproblem multiple times, which is inefficient.
Example: Naive Fibonacci (Exponential Time)
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # Output: 55
❌ This solution recalculates the same values many times.
def fib_memo(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
print(fib_memo(10)) # Output: 55
Build the solution from the ground up.
def fib_tab(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
print(fib_tab(10)) # Output: 55
Given weights and values, determine the maximum value you can carry in a bag of capacity W.
def knapsack(W, weights, values, n):
dp = [[0 for _ in range(W + 1)] for _ in range(n + 1)]
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
dp[i][w] = 0
elif weights[i - 1] <= w:
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w])
else:
dp[i][w] = dp[i - 1][w]
return dp[n][W]
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
print(knapsack(capacity, weights, values, len(values))) # Output: 220
Problem | Description |
---|---|
Fibonacci Numbers | Basic DP example |
Climbing Stairs | Count ways to reach top |
0/1 Knapsack | Max value under capacity |
Longest Common Subsequence | Similar strings analysis |
Coin Change | Fewest coins to make amount |
🔗 References
Python DP Examples
GeeksforGeeks DP Guide
Created with ❤️ by Pynfinity