You are given an array of integers.
You need to find the contiguous subarray of the maximum sum in . The subarray should not contain the number . Please find the maximum sum that is possible.
Note 1: The subarray can also be empty.
Note 2: The answer will fit in 32 bit-signed integer.
Input Format
The first line contains the integer . The next line contains integers representing the numbers in the array.
Constraints
Output Format
Output a single line representing the maximum sum that can be obtained.
Sample Input
5
3 4 0 1 2
Sample Output
7
Explanation
The subarray with the maximum sum that doesn’t contain a is .
Hence, the sum is.
题目大意:
求不包括元素0的最大子序列和。
题目解析:
遍历序列,当遍历到第i个元素时,判断前面的连续子序列的和是否大于0,有就加上;遍历到0元素时,自动清零。
具体代码:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
#define MAXN 100010
int A[MAXN];
int main() {
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
cin>>A[i];
int maxSum=0,maxHere=0;
for(int i=0;i<n;i++){
if(A[i]==0)
maxHere=0;
else if(maxHere<=0)
maxHere=A[i];
else
maxHere+=A[i];
maxSum=max(maxHere,maxSum);
}
cout<<maxSum<<endl;
return 0;
}