Created
October 10, 2013 22:38
-
-
Save nucleartide/6926693 to your computer and use it in GitHub Desktop.
Solution to maximum consecutive sum problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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