这道题应该用dp才对,但是发现全部TLE(dp不是以快著称吗)……
来看看,一股浓郁的前缀和气味,上面说一段,并且还说和,前缀和就是用来求某一个区间中元素的和的啊!!
立马写一个:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[n + 10];
int s[1000005];
for (int i = 0; i < n; i++) {
cin >> a[i];
if (i != 0) {
s[i] = s[i - 1] + a[i];
} else {
s[i] = a[i];
}
}
int ans = -99999999999;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
ans = max(ans, s[j] - s[i] + a[i]);
}
}
cout << ans << endl;
return 0;
}
TLE了(早就预料到了),为啥呢??因为代码的最后有两个循环套在了一起,速度大打折扣,这时,就要让整个代码不出现循环嵌套,于是又优化了一下(加入了b数组):
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, a[200001], b[200001], s[200001], minn = 0, ans = -999999999;
memset(a, 0, sizeof a);
memset(b, 0, sizeof b);
memset(s, 0, sizeof s);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
s[i] = s[i - 1] + a[i];
}
b[0] = a[0];
minn = min(0, s[0]);
for (int i = 1; i < n; i++) {
b[i] = s[i] - minn;
minn = min(minn, s[i]);
}
for (int i = 0; i < n; i++) ans = max(ans, b[i]);
cout << ans << endl;
return 0;
}
真香,过了