思路:
DPf[i][j]
表示从前i
个元素中选j
个且第i
个元素被选的最大元素和
初始化:f[i][j] = -1e15, f[0][0] = 0
状态转移:
因为题目要求每k
个元素一定有一个被选,故第i
个元素被选,上一个被选的一定是p ∈Math.max(0, i - k), i - 1
范围内f[i][j] = Math.max(f[i][j], f[p][j - 1] + a[i]
结果:
最后一个被选元素一定位于最后k
个元素中,遍历找最大值
import java.util.*;
public class Main {
static final int N = 211;
static int[] a = new int[N];
static long[][] f = new long[N][N];
static int n, k, m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
m = sc.nextInt();
for (int i = 1; i <= n; i++)
a[i] = sc.nextInt();
for (int i = 0; i <= n; i++)
Arrays.fill(f[i], (long)(-1e15));
f[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= Math.min(i, m); j++) {
for (int p = Math.max(0, i - k); p < i; p++)
f[i][j] = Math.max(f[i][j], f[p][j - 1] + a[i]);
}
}
long ans = -1;
for (int i = Math.max(1, n - k + 1); i <= n; i++)
ans = Math.max(ans, f[i][m]);
System.out.println(ans);
}
}