
线性DP经典题。
dp[i]表示以i为结尾最大连续和,状态转移方程dp[i] = max (a[i] , dp[i - 1] + a[i])
AC代码:
#include<cstdio> #define max(x, y) (x) > (y) ? (x) : (y) const int maxn = 1e6 + 5; const int inf = 1 << 30; int dp[maxn]; int main(){ int n, T; scanf("%d", &T); dp[0] = 0; while(T--){ scanf("%d", &n); int ans = -inf, x; for(int i = 1; i <= n; ++i){ scanf("%d", &x); dp[i] = max(x, dp[i - 1] + x); ans = max(ans, dp[i]); } printf("%d\n", ans); } return 0; }
如有不当之处欢迎指出!