forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request TheAlgorithms#61 from dhruvsaini/patch-3
Create knapsack.py
- Loading branch information
Showing
1 changed file
with
14 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
""" | ||
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. | ||
""" | ||
def knapsack(W, wt, val, n): | ||
dp = [[0 for i in range(W+1)]for j in range(n+1)] | ||
|
||
for i in range(1,n+1): | ||
for w in range(1,W+1): | ||
if(wt[i-1]<=w): | ||
dp[i][w] = max(val[i-1]+dp[i-1][w-wt[i-1]],dp[i-1][w]) | ||
else: | ||
dp[i][w] = dp[i-1][w] | ||
|
||
return dp[n][w] |