Created
October 11, 2013 16:01
-
-
Save albertelwin/6937372 to your computer and use it in GitHub Desktop.
Programming Interview Practice - Max Consecutive Sum - 11/10/13
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
/* | |
Programming Interview Practice - Max Consecutive Sum | |
Albert Elwin | |
Website: http://albertelw.in | |
Email: [email protected] | |
*/ | |
#include <cstdio> | |
#include <vector> | |
std::vector<int> const findLargestSumOfContiguousElements(std::vector<int> const & initialArray) | |
{ | |
int currentSum = 0; | |
for(auto i : initialArray) { | |
currentSum += i; | |
} | |
unsigned int minId = 0; | |
unsigned int maxId = initialArray.size() - 1; | |
std::printf("Initial sum: %d (%u, %u)\n", currentSum, minId, maxId); | |
unsigned int startId = minId; | |
unsigned int endId = maxId; | |
bool doLeft = true; | |
while(startId < endId) | |
{ | |
startId = (doLeft) ? startId + 1 : startId; | |
endId = (!doLeft) ? endId - 1 : endId; | |
doLeft = !doLeft; | |
int nextSum = 0; | |
for(auto i = initialArray.begin() + startId; i < initialArray.begin() + endId; i++) { | |
nextSum += (*i); | |
} | |
std::printf("Next sum: %d (%u, %u)\n", nextSum, startId, endId); | |
if(nextSum > currentSum) | |
{ | |
currentSum = nextSum; | |
minId = startId; | |
maxId = endId; | |
} | |
} | |
std::printf("Largest sum: %d (%u, %u)\n", currentSum, minId, maxId); | |
return std::vector<int>(initialArray.begin() + minId, initialArray.begin() + maxId); | |
} | |
int main() | |
{ | |
std::vector<int> const vec = findLargestSumOfContiguousElements({-1, 5, 6, -2, 20, -50, 4}); | |
std::printf("Largest contiguous sum: "); | |
for(auto i : vec) { | |
std::printf("%d ", i); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment