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