Last active
July 22, 2017 02:11
-
-
Save tamarous/b9c1093f860acf9acaeb47a16163f7d2 to your computer and use it in GitHub Desktop.
最简单的求最大子序列和算法,时间复杂度:O(N)
This file contains hidden or 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
/************************************************************************* | |
> 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