解法一:
双指针,没必要开数组直接边输边算,max至少要2个数,补一个数时的特判
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define endl '\n'
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
long long n, a, cnt = 0, maxsum = 0;
cin >> n;
cin >> a; n--;
cnt += a;
maxsum = cnt;
while (n--) {
cin >> a;
cnt += a;
maxsum = max(maxsum, cnt);
if (cnt <= 0) cnt = 0;
}
cout << maxsum << endl;
return 0;
}
解法二:
dp[i]:以vec[i]为段尾的最大子段和
状态转移方程:
base condition:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define endl '\n'
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
vector<long long> vec(n, 0);
vector<long long> dp(n, 0);
for (int i = 0; i < n; i++) cin >> vec[i];
dp[0] = vec[0];
for (int i = 1; i < n; i++) {
dp[i] = max(dp[i - 1] + vec[i], vec[i]);
}
cout << *max_element(dp.begin(), dp.end()) << endl;
return 0;
}