http://www.lintcode.com/en/problem/maximum-subarray-iii/#
找出k个不重叠的子数组,且和最大
不太明显的DP,dp[i][j]为分成i个子数组,原数组长度为j。外层i遍历k,内层遍历从i ~ len。内层的local为当前分割之后的最后一个子数组的结尾位置为nums[j - 1]。
当i == j的时候注意一下
public class Solution {
/**
* @param nums: A list of integers
* @param k: An integer denote to find k non-overlapping subarrays
* @return: An integer denote the sum of max k non-overlapping subarrays
*/
public int maxSubArray(int[] nums, int k) {
// write your code here
if (nums == null || nums.length < k) {
return 0;
}
int[][] dp = new int[k + 1][nums.length + 1];
for (int i = 1; i <= k; i++) {
int local = Integer.MIN_VALUE;
for (int j = i; j <= nums.length; j++) {
local = Math.max(local, dp[i - 1][j - 1]) + nums[j - 1];
if (j == i) {
dp[i][j] = local;
} else {
dp[i][j] = Math.max(local, dp[i][j - 1]);
}
}
}
return dp[k][nums.length];
}
}