题解 | #最大序列和#
最大序列和
https://www.nowcoder.com/practice/df219d60a7af4171a981ef56bd597f7b
#include <iostream>
using namespace std;
int main() {
int n;
while (cin >> n) {
int a[n];
long long sum = 0;
long long max = 0;
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) {
if (sum + a[i] <= 0) {//部分和一旦为负,直接清空,重新计算
sum = 0;
} else if (a[i] > 0) {//a[i]大于零计入部分和
sum += a[i];
if (max < sum)//max为当前最大部分和,由于sum可能清空过,所以要和max比较一下
max = sum;
} else if (a[i] <= 0) {//有可能只是某一个值为负但后面的值依然使得部分和更大,所以在不使sum小于零的前提下,更新sum
sum += a[i];
}
}
int num = 0;
int max_ = a[0];//全负时只需找出最大值即可
if (a[0] <= 0) {
for (int i = 1; i < n; i++) {
if (a[i] <= 0)
num++;
if (max_ < a[i])
max_ = a[i];
}
}
if (num == n - 1)//判断是否全为负
cout << max_ << endl;
else
cout << max << endl;
}
}
// 64 位输出请用 printf("%lld")
#虽蠢但对#
