File tree
Expand file treeCollapse file tree1 file changed
+14
-0
lines changed Expand file treeCollapse file tree1 file changed
+14
-0
lines changed Original file line number | Diff line number | Diff line change |
---|
|
| 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] |
You can’t perform that action at this time.
0 commit comments