Skip to content

Commit 5a30597

Browse files
authored
Create knapsack.py
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
1 parent 7a08d09 commit 5a30597

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

dynamic_programming/knapsack.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"""
2+
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
3+
"""
4+
def knapsack(W, wt, val, n):
5+
dp = [[0 for i in range(W+1)]for j in range(n+1)]
6+
7+
for i in range(1,n+1):
8+
for w in range(1,W+1):
9+
if(wt[i-1]<=w):
10+
dp[i][w] = max(val[i-1]+dp[i-1][w-wt[i-1]],dp[i-1][w])
11+
else:
12+
dp[i][w] = dp[i-1][w]
13+
14+
return dp[n][w]

0 commit comments

Comments
 (0)