N个数,允许将前连续任意个数变化为其相反数,也允许把后连续任意个数变为相反数,求最大和
令dp[i][0]前i个数操作后能得到的最大值,dp[i][1]出去前i-1个数操作后能得到的最大值
注意初始化,不然对于答案为无需操作的情况会出错
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define INF 0x3f3f3f3f using namespace std; typedef long long LL; const int maxn = 1e5 + 10; int A[maxn]; int dp[maxn][2]; int sum[maxn]; int N; int main() { scanf("%d", &N); for (int i = 1; i <= N; i++) { scanf("%d", &A[i]); sum[i] = sum[i - 1] + A[i]; } int tmp = -INF; for (int i = 1; i <= N; i++) { tmp = max(tmp, -2 * sum[i]); dp[i][0] = sum[i] + tmp; } tmp = -INF; for (int i = N; i > 0; i--) { tmp = max(tmp, -2 * (sum[N] - sum[i - 1])); dp[i][1] = (sum[N] - sum[i - 1]) + tmp; } int ans = sum[N];// for (int i = 0; i <= N; i++) { ans = max(ans, dp[i][0] + dp[i + 1][1]); } printf("%d\n", ans); return 0; }
原文地址:https://www.cnblogs.com/xFANx/p/8448187.html
时间: 2024-11-14 12:45:04