Last active
August 29, 2015 14:05
-
-
Save ivycheung1208/1843c9da901d1c352a13 to your computer and use it in GitHub Desktop.
CC150 17.8
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
/* CC150 17.8 */ | |
// find the contiguous sequence with the largest sum, return the sum | |
// book solution | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
// what if required to return start and end indices of the sequence?!! | |
int maxSum(vector<int> arr) | |
{ | |
// no need to shrink the array! doesn't affect the algorithm | |
int sum = 0, maxSum = 0; | |
for (auto begin = arr.cbegin(); begin != arr.cend(); ++begin) { | |
sum += *begin; | |
if (sum < 0) // disgard previous sequence and reset sum | |
sum = 0; | |
else { // still addable, keep searching | |
if (sum > maxSum) | |
maxSum = sum; | |
} | |
} | |
return maxSum; // return 0 if the whole array is negative | |
} | |
int main() | |
{ | |
vector<int> arr; | |
int data; | |
while (cin >> data) | |
arr.push_back(data); | |
cout << maxSum(arr) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment