方法一
递推 + 最小空间使用
直接上代码
#include<iostream>
#include<algorithm>
using namespace std;
int n, a, b, ret = -1e9;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a;
if (i == 1) {
b = a;
}
else {
b = max(a + b, a);
ret = max(b, ret);
}
}
cout << ret << endl;
return 0;
}
方法二
动态规划
dp[i] = max(dp[i - 1] + a[i] , a[i])
#include<iostream>
#include<algorithm>
using namespace std;
int n, a[2005], dp[2005], sum = -1e9;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
dp[i] = max(dp[i - 1] + a[i], a[i]);
sum = max(dp[i], sum);
}
cout << sum << endl;
return 0;
}