Skip to content

Commit 60d0cea

Browse files
committed
Implementation of the Knapsack Problem Solver #11401
1 parent 1f368da commit 60d0cea

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

knapsack/dp_knapsack.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def knapsack_dp(capacity: int, weights: list[int], values: list[int]) -> int:
2+
"""
3+
Returns the maximum value that can be put in a knapsack of a given capacity,
4+
with each weight having a specific value.
5+
6+
Uses a dynamic programming approach to solve the 0/1 Knapsack Problem.
7+
8+
>>> capacity = 50
9+
>>> values = [60, 100, 120]
10+
>>> weights = [10, 20, 30]
11+
>>> knapsack_dp(capacity, weights, values)
12+
220
13+
"""
14+
n = len(weights)
15+
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
16+
17+
# Build table dp[][] in a bottom-up manner
18+
for i in range(1, n + 1):
19+
for w in range(1, capacity + 1):
20+
if weights[i - 1] <= w:
21+
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w])
22+
else:
23+
dp[i][w] = dp[i - 1][w]
24+
25+
return dp[n][capacity]
26+
27+
28+
if __name__ == "__main__":
29+
import doctest
30+
doctest.testmod()

0 commit comments

Comments
 (0)