Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- const int MAXN = 10; //元素个数
- int a[MAXN] = {-10, 1, 2, 3, 4, -5, -23, 3, 7, -21};
- int main(){
- int thisSum = 0, maxSum = 0;
- //时间复杂度:O(n)
- for(int i = 0; i < MAXN; i++){
- thisSum += a[i];
- //如果发现更大的子段和,那么更新maxSum
- if(thisSum > maxSum) maxSum = thisSum;
- //如果当前子段和小于0,那么丢弃
- if(thisSum < 0) thisSum = 0;
- }
- cout<<maxSum<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement