有两种方式:
1.在首尾之间
2.在尾首之间
对于第一种直接来dp就好,第二种需要将其数组全部取负,然后取到其最大值(肯定是负数的最大值)然后dp即可,最后比较这两个答案谁比较大就输出哪个
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 #define max(a,b) a>b?a:b 5 6 const int maxn = 50000 + 5; 7 int a[maxn]; 8 int n; 9 long long dp[maxn]; 10 11 long long Sum(int a[]){ 12 dp[1] = a[1]; 13 long long ans = 0; 14 for (int i = 1; i <= n; i++){ 15 dp[i] = max(dp[i - 1] + a[i], a[i]); 16 ans = max(ans, dp[i]); 17 } 18 return ans; 19 } 20 21 int main(){ 22 ios::sync_with_stdio(false); 23 cin >> n; 24 long long sum = 0; 25 for (int i = 1; i <= n; i++){ 26 cin >> a[i]; 27 sum += a[i]; 28 } 29 long long ans1 = Sum(a); 30 for (int i = 1; i <= n; i++){ 31 a[i] = -a[i]; 32 } 33 long long ans2 = Sum(a); 34 long long Ans = max(ans1, ans2 + sum); 35 cout << Ans << endl; 36 37 return 0; 38 }