Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Last active August 29, 2015 14:05
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 ivycheung1208/1843c9da901d1c352a13 to your computer and use it in GitHub Desktop.
Save ivycheung1208/1843c9da901d1c352a13 to your computer and use it in GitHub Desktop.
CC150 17.8
/* 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