题意:没什么毛病,就是求一个最大子序列和的问题。
思路: 两种种思路吧——暴力、dp。暴力就直接利用前缀和求个最大差值,不过还是很意外1e4的这个复杂度按理说是会超时的,但这个题可能数据比较水竟然400ms的限制也能过。
暴力代码:
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e5+10;
int n, a[N], pre[N], ne;
signed main()
{
cin >> n;
for(int i = 1; i <= n; i ++){
cin >> a[i];
pre[i] = pre[i-1]+a[i];
if(a[i]<0) ne ++;
}
if(ne==n){
cout << 0 << " " << a[1] << " " << a[n] << endl;
return 0;
}
int ans = 0, bg = 0, ed = 0;
for(int i = 1; i <= n; i ++){
for(int j = i; j <= n; j ++){
int sum = pre[j]-pre[i-1];
if(sum>ans){
ans = sum;
bg = a[i], ed = a[j];
}
}
}
cout << ans << " " << bg << " " << ed << endl;
return 0;
}
dp代码:
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e5+10;
int n, a[N];
signed main()
{
cin >> n;
int ans = -1, sum = 0, idx = 1;
int bg = 1, ed = n;
for(int i = 1; i <= n; i ++){
cin >> a[i];
sum += a[i];
if(sum<0){
idx = i+1;
sum = 0;
}
else if(sum>ans){
ans = sum;
bg = idx;
ed = i;
}
}
cout << max(0ll, ans) << " " << a[bg] << " " << a[ed] << endl;
return 0;
}