43. 最大子数组 III
给定一个整数数组和一个整数 k,找出 k 个不重叠子数组使得它们的和最大。每个子数组的数字在数组中的位置应该是连续的。
返回最大的和。
样例
样例1
输入:
List = [1,2,3]
k = 1
输出: 6
说明: 1 + 2 + 3 = 6
样例2
输入:
List = [-1,4,-2,3,-2,3]
k = 2
输出: 8
说明: 4 + (3 + -2 + 3) = 8
注意事项
子数组最少包含一个数
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) {
if (nums.length < k) {
return 0;
}
int len = nums.length;
int[][] localMax = new int[len+1][k+1];
int[][] globalMax = new int[len+1][k+1];
for (int i = 1; i <= len; i++)
{
//j must be less or equal to i, since i is smaller, it can not be partitioned into j groups.
for (int j = 1; j <= i && j <= k; j++)
{
//Here i = j-1, means i < j, so it's not a valid case, we use Integer.MIN_VALUE
//why we need this, since the latter may use this one to do comparison, we can not use 0
localMax[j-1][j] = Integer.MIN_VALUE;
globalMax[j-1][j] = Integer.MIN_VALUE;
localMax[i][j] = Math.max(globalMax[i-1][j-1], localMax[i-1][j]) + nums[i-1];
globalMax[i][j] = Math.max(globalMax[i-1][j], localMax[i][j]);
}
}
return globalMax[len][k];
}
}