题目
给定长度为 n 的序列,将其分为 m 个不相交的字段,求这 m 个字段的和的最大值。
AC 代码
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(), m = scanner.nextInt();
int[] array = new int[n + 1];
for (int i = 1; i <= n; i++)
array[i] = scanner.nextInt();
int res = 0;
int[] dp = new int[n + 1];
int[] maxArray = new int[n + 1];
for (int i = 1; i <= m; i++) {
res = Integer.MIN_VALUE;
for (int j = i; j <= n; j++) {
// if (i == j) dp[j] = maxArray[j - 1] + array[i];
// else dp[j] = Math.max(dp[j - 1], maxArray[j - 1]) + array[i];
dp[j] = Math.max(dp[j - 1], maxArray[j - 1]) + array[j];
maxArray[j-1] = res;
if (res < dp[j]) res = dp[j];
}
}
System.out.println(res);
}
}