We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 9f317eb commit e7af618Copy full SHA for e7af618
1_algorithm_design_and_techniques/week5_and_6_dynamic_programming/knapsack.py
@@ -0,0 +1,22 @@
1
+import sys
2
+
3
+def optimal_weight(W, w):
4
5
+ V = [[0 for j in range(W + 1)] for i in range(len(w) + 1)]
6
7
+ for i in range(1, len(w) + 1):
8
+ for j in range(1, W + 1):
9
+ V[i][j] = V[i - 1][j]
10
+ if w[i - 1] <= j:
11
+ val = V[i - 1][j - w[i - 1]] + w[i - 1]
12
+ if val > V[i][j]:
13
+ V[i][j] = val
14
15
+ return V[len(w)][W]
16
17
+if __name__ == '__main__':
18
+ input = sys.stdin.read()
19
+ W, n, *w = list(map(int, input.split()))
20
+ print(optimal_weight(W, w))
21
22
+#python3 knapsack.py <<< "10 3 1 4 8" 9
0 commit comments