forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdp_knapsack.py
33 lines (26 loc) · 967 Bytes
/
dp_knapsack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def knapsack_dp(capacity: int, weights: list[int], values: list[int]) -> int:
"""
Returns the maximum value that can be put in a knapsack of a given capacity,
with each weight having a specific value.
Uses a dynamic programming approach to solve the 0/1 Knapsack Problem.
>>> capacity = 50
>>> values = [60, 100, 120]
>>> weights = [10, 20, 30]
>>> knapsack_dp(capacity, weights, values)
220
"""
n = len(weights)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
# Build table dp[][] in a bottom-up manner
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if 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][capacity]
if __name__ == "__main__":
import doctest
doctest.testmod()