Skip to content

Commit 01c18e5

Browse files
authored
Create DynamicProgramming-knapsack_0_1.py
1 parent f77521b commit 01c18e5

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

DynamicProgramming-knapsack_0_1.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def knapsack_0_1(W, n, weights, values):
2+
dp = [[0 for x in range(n+1)] for x in range(W+1)]
3+
for x in range(1,W+1):
4+
for i in range(1,n+1):
5+
dp[x][i]=dp[x][i-1]
6+
wi = weights[i-1]
7+
vi = values[i-1]
8+
if x >= wi:
9+
dp[x][i] = max(dp[x][i] , dp[x-wi][i-1] + vi)
10+
11+
return dp[W][n]
12+
13+
print(knapsack_0_1(10, 5 ,[4, 9, 3, 5, 7], [10, 25, 13, 20, 8] ))

0 commit comments

Comments
 (0)