You are given an array a1,a2,…,an and two integers m and k.
You can choose some subarray al,al+1,…,ar−1,ar
The cost of subarray al,al+1,…,ar−1,ar is equal to , where ⌈x⌉is the least integer greater than or equal to x.
The cost of empty subarray is equal to zero.
For example, if m=3, k=10 and a=[2,−4,15,−3,4,8,3], then the cost of some subarrays are:
Your task is to find the maximum cost of some subarray (possibly empty) of array aa.
The first line contains three integers n, m, and k (1≤n≤,1≤m≤10,1≤k≤).
The second line contains n integers a1,a2,…,an ().
Print the maximum cost of some subarray of array a.
7 3 10
2 -4 15 -3 4 8 3
7
5 2 1000
-13 -4 -9 -20 -11
0
这题我一开始想要通过修改最大子列和的在线处理算法来写这题,样例都过但是第三个测试数据wa了,我原来觉得这样写肯定没错的,后来补题时发现想法是错的,因为在线处理是把没用的一段直接丢掉,但是这题里的r - l + 1会对结果产生影响,可能只丢掉一小段,结果会更大,直接打表前缀和暴力枚举亲测超时,由于子序列的长度会对值产生影响,所以我们用dp来枚举每种情况,对于每个元素都有m种状态,当前元素在不同状态对后面的影响是不同的,所以我们可以开一个n* m大小的dp数组dp[i][j],代表第i个元素,在长度对m取模后的j位置时的最大值。
状态转移方程为
(j == 1)dp[i][j] = max(a[i] - k, dp[i - 1][m] + a[i] - k);
(j > 1)dp[i][j] = dp[i - 1][j - 1] + a[i];
#include
#include
using namespace std;
typedef long long ll;
const int N = 3e5 + 5;
ll a[N];
//ll sum[N];
ll dp[N][20];
int main()
{
int n, m, k;
cin >> n >> m >> k;
a[0] = 0;
for (int i = 1; i <= m; i ++)dp[0][i] = -1e10;
ll ans = 0;
for (int i = 1; i <= n; i ++){
scanf("%lld", &a[i]);
for (int j = 1; j <= m; j ++){
if (j == 1)dp[i][j] = max(a[i] - k, dp[i - 1][m] + a[i] - k);
else dp[i][j] = dp[i - 1][j - 1] + a[i];
ans = max(ans, dp[i][j]);
}
}
printf("%lld\n", ans);
return 0;
}