summaryrefslogtreecommitdiff
path: root/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py
diff options
context:
space:
mode:
Diffstat (limited to 'AlgoDesignAndTechniqueEdxPython/sources/knapsack.py')
-rw-r--r--AlgoDesignAndTechniqueEdxPython/sources/knapsack.py22
1 files changed, 22 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py b/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py
new file mode 100644
index 0000000..24e5e92
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py
@@ -0,0 +1,22 @@
+# Uses python3
+import sys
+
+
+def optimalWeight(W, w2):
+ j = len(w2)
+ value = [[0 for _ in range(j + 1)] for _ in range(W + 1)]
+
+ for i in range(1, j + 1):
+ for w in range(1, W + 1):
+ value[w][i] = value[w][i - 1]
+ if w2[i - 1] <= w:
+ val = value[w - w2[i - 1]][i - 1] + w2[i - 1]
+ if value[w][i] < val:
+ value[w][i] = val
+ return value[W][j]
+
+
+if __name__ == '__main__':
+ input = sys.stdin.read()
+ W, n, *w = list(map(int, input.split()))
+ print(optimalWeight(W, w))