Skip to content

Instantly share code, notes, and snippets.

@nucleartide
Created October 10, 2013 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nucleartide/6926693 to your computer and use it in GitHub Desktop.
Save nucleartide/6926693 to your computer and use it in GitHub Desktop.
Solution to maximum consecutive sum problem
#include <vector>
#include <iostream>
int max_consecutive_sum(const std::vector<int> &arr) {
if (arr.size() == 0) {
return 0;
}
std::vector<int> sums(arr.size(), 0);
int maxConsecutiveSumIndex = 0;
for (int i = 0; i < arr.size(); ++i) {
if (i > 0) {
sums[i] = arr[i] + sums[i-1];
if (sums[i] > sums[i-1]) {
maxConsecutiveSumIndex = i;
}
} else {
sums[i] = arr[i];
}
}
int min = 0;
for (int i = 0; i < maxConsecutiveSumIndex; ++i) {
if (sums[i] < min) {
min = sums[i];
}
}
if (min < 0) {
return sums[maxConsecutiveSumIndex] - min;
} else {
return sums[maxConsecutiveSumIndex];
}
}
int main() {
std::vector<int> test1;
test1.push_back(1);
test1.push_back(-5);
test1.push_back(4);
test1.push_back(10);
test1.push_back(-3);
test1.push_back(7);
test1.push_back(-5);
std::vector<int> test2;
std::vector<int> test3;
test3.push_back(4);
std::cout << max_consecutive_sum(test1) << std::endl;
std::cout << max_consecutive_sum(test2) << std::endl;
std::cout << max_consecutive_sum(test3) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment