Skip to content

Instantly share code, notes, and snippets.

@tamarous
Last active July 22, 2017 02:11
Show Gist options
  • Save tamarous/b9c1093f860acf9acaeb47a16163f7d2 to your computer and use it in GitHub Desktop.
Save tamarous/b9c1093f860acf9acaeb47a16163f7d2 to your computer and use it in GitHub Desktop.
最简单的求最大子序列和算法,时间复杂度:O(N)
/*************************************************************************
> File Name: maxSequenceSumSimplest.cpp
> Author:
> Mail:
> Created Time: 2016年10月10日 星期一 11时02分21秒
************************************************************************/
#include<iostream>
using namespace std;
int maxSequenceSum(const int a[],int N)
{
int sum =0, max = 0;
for(int i = 0;i<N;i++)
{
sum += a[i];
if (sum > max)
{
max = sum;
}
else if (sum < 0)
sum = 0;
}
return max;
}
int main()
{
int a[] = {4,-3,5,-2,-1,2,6,-2};
int length = sizeof(a)/sizeof(a[0]);
int max = maxSequenceSum(a,length);
cout << "max is " << max << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment