summaryrefslogtreecommitdiff
path: root/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py
diff options
context:
space:
mode:
authorHaidong Ji2018-12-26 18:15:59 -0600
committerHaidong Ji2018-12-26 18:15:59 -0600
commita8bdf7580ae3c6b55554b965810aeb48517d7af1 (patch)
treea594fa7535b24b4c0d7a5de81a49829e9a395772 /AlgoDesignAndTechniqueEdxPython/sources/knapsack.py
parent61ffe2a9e5fd066dae82a32185bbfe821696bd8a (diff)
Knapsack maximize gold done!
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))