Skip to content

Commit 9f01007

Browse files
authored
Create Knapsack_problem.py
1 parent f581e7e commit 9f01007

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Knapsack_problem.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# A Dynamic Programming based Python
2+
# Program for 0-1 Knapsack problem
3+
# Returns the maximum value that can
4+
# be put in a knapsack of capacity W
5+
def knapSack(W, wt, val, n):
6+
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
7+
8+
# Build table K[][] in bottom up manner
9+
for i in range(n + 1):
10+
for w in range(W + 1):
11+
if i == 0 or w == 0:
12+
K[i][w] = 0
13+
elif wt[i-1] <= w:
14+
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
15+
else:
16+
K[i][w] = K[i-1][w]
17+
18+
return K[n][W]
19+
20+
# Driver program to test above function
21+
val = [60, 100, 120]
22+
wt = [10, 20, 30]
23+
W = 50
24+
n = len(val)
25+
print(knapSack(W, wt, val, n))
26+
27+
# This code is contributed by Vanasetty Rohit

0 commit comments

Comments
 (0)