summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 19:10:05 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 20:30:16 +0100
commit2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b (patch)
tree79e6a3900fb3a288962cabd572ed942fc77b74c5 /01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands
parente72410168143db1b79ee30e47d68cca2d730f740 (diff)
downloadcoursera-2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b.zip
coursera-2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b.tar.gz
Algorithms : complete 01-algorithmic_toolbox 02-greedy_algorithms
Diffstat (limited to '01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands')
-rw-r--r--01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands/different_summands.cpp16
1 files changed, 15 insertions, 1 deletions
diff --git a/01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands/different_summands.cpp b/01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands/different_summands.cpp
index 0f8b4cb..fe36866 100644
--- a/01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands/different_summands.cpp
+++ b/01-algorithmic_toolbox/02-greedy_algorithms/05-different_summands/different_summands.cpp
@@ -5,7 +5,20 @@ using std::vector;
vector<int> optimal_summands(int n) {
vector<int> summands;
- //write your code here
+ int s = 0;
+ for (int i = 1; ; i++) {
+ s += i;
+ if (s == n) {
+ summands.push_back(i);
+ break;
+ }
+ if (s > n) {
+ s -= (i + i - 1);
+ summands[summands.size() - 1] = (n - s);
+ break;
+ }
+ summands.push_back(i);
+ }
return summands;
}
@@ -17,4 +30,5 @@ int main() {
for (size_t i = 0; i < summands.size(); ++i) {
std::cout << summands[i] << ' ';
}
+ std::cout << '\n';
}