//特殊情况 为负值即输出开头结尾即可
#include<iostream>
#include<cstdio>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 10000+5;
int main() {
int n, ans =-inf;
cin >> n;
int a[N];
int sum[N], l=0, r=n-1, ansl=0, ansr=0;
sum[0] = 0;
for(int i=1; i<=n; i++) {
cin >> a[i];
if(sum[i-1]+a[i] < a[i]) {
l = i-1;//下标
r = i-1;
sum[i] = a[i];
} else r = i-1, sum[i] = sum[i-1]+a[i];
if(sum[i] > ans) {
ansl = l;
ansr = r;
ans = sum[i];
}
}
if(ans < 0) cout << 0 << " " << a[1] << " " << a[n] << endl;
else
cout << ans << " " << a[ansl+1] << " " << a[ansr+1] << endl;
return 0;
}

本文深入探讨了一种高效算法,用于寻找数组中具有最大和的连续子数组,并详细解释了其实现过程。通过动态规划思想,算法能够在O(n)的时间复杂度内找到最优解,避免了传统穷举法的高时间成本。
1390

被折叠的 条评论
为什么被折叠?



