summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 21:18:32 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 21:18:32 +0100
commitbc75b20fc0e80d6037ee14e3dccc2d88823f5f2f (patch)
treea45d61c5be8df717a28904d434287b88d94a1843 /01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp
parent36260c39bee50e6160c99e240fcad63402e39346 (diff)
downloadcoursera-bc75b20fc0e80d6037ee14e3dccc2d88823f5f2f.zip
coursera-bc75b20fc0e80d6037ee14e3dccc2d88823f5f2f.tar.gz
Algorithms : add 01-algorithmic_toolbox 04-dynamic_programming
Diffstat (limited to '01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp')
-rw-r--r--01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp25
1 files changed, 25 insertions, 0 deletions
diff --git a/01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp b/01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp
new file mode 100644
index 0000000..c284560
--- /dev/null
+++ b/01-algorithmic_toolbox/04-dynamic_programming/02-knapsack/knapsack.cpp
@@ -0,0 +1,25 @@
+#include <iostream>
+#include <vector>
+
+using std::vector;
+
+int optimal_weight(int W, const vector<int> &w) {
+ //write your code here
+ int current_weight = 0;
+ for (size_t i = 0; i < w.size(); ++i) {
+ if (current_weight + w[i] <= W) {
+ current_weight += w[i];
+ }
+ }
+ return current_weight;
+}
+
+int main() {
+ int n, W;
+ std::cin >> W >> n;
+ vector<int> w(n);
+ for (int i = 0; i < n; i++) {
+ std::cin >> w[i];
+ }
+ std::cout << optimal_weight(W, w) << '\n';
+}