思路:
使用动态规划,在经典的最大子段和解法基础上进行扩展。dp[i][j]表示以第i个数为结尾,并且长度模m等于j的所有子段的最大cost。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const ll INF = 0x3f3f3f3f3f3f3f3f; 5 const int N = 300005; 6 ll a[N], dp[N][11]; 7 int main() 8 { 9 int n; ll m, k; 10 while (cin >> n >> m >> k) 11 { 12 memset(dp, 0, sizeof dp); 13 for (int i = 1; i <= n; i++) cin >> a[i]; 14 ll res = 0; 15 dp[0][0] = -k; 16 for (int i = 1; i < m; i++) dp[0][i] = -INF; 17 for (int i = 1; i <= n; i++) 18 { 19 for (int j = 0; j < m; j++) 20 { 21 if (j == (m == 1 ? 0 : 1)) 22 { 23 dp[i][j] = max(dp[i - 1][0] + a[i] - k, a[i] - k); 24 } 25 else 26 { 27 dp[i][j] = max(dp[i - 1][(j - 1 + m) % m] + a[i], a[i] - k); 28 } 29 res = max(res, dp[i][j]); 30 } 31 } 32 cout << res << endl; 33 } 34 return 0; 35 }
来源:https://www.cnblogs.com/wangyiming/p/12031533.html