From 5a3059784f71d93a973c30c588287bfe50d6710e Mon Sep 17 00:00:00 2001 From: dhruvsaini Date: Tue, 3 Jan 2017 16:50:13 +0530 Subject: [PATCH] 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. --- dynamic_programming/knapsack.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 dynamic_programming/knapsack.py diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py new file mode 100644 index 000000000..a1e4f0d80 --- /dev/null +++ b/dynamic_programming/knapsack.py @@ -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]