大家可以参考这位老哥的分析,我就不写了
股票买卖 IV
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] temp = reader.readLine().split(" ");
int n = Integer.parseInt(temp[0]);
int k = Integer.parseInt(temp[1]);
temp = reader.readLine().split(" ");
int[] w = new int[n+1];
for (int i = 0; i < n; i++) {
w[i+1] = Integer.parseInt(temp[i]);
}
int[][][] f = new int[2][100010][110];
//我为了方便初始化数据,改了一下状态数组的定义顺序
for (int i = 0; i < n + 1; i++) {
Arrays.fill(f[0][i], -0x3f3f3f3f);
Arrays.fill(f[1][i], -0x3f3f3f3f);
}
f[0][0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= k; j++) {
f[0][i][j] = f[0][i-1][j];
if (j > 0){
f[0][i][j] = Math.max(f[0][i][j], f[1][i-1][j-1]+w[i]);
}
f[1][i][j] = Math.max(f[1][i-1][j], f[0][i-1][j]-w[i]);
}
}
int res = 0;
for (int i = 0; i <= k; i++) {
res = Math.max(res, f[0][n][i]);
}
System.out.println(res);
}
}