Maximum Subarray III
Description
Analysis
Solution
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 == 0) return 0;
int n = nums.length;
int[][] localMax = new int[n + 1][k + 1];
int[][] globalMax = new int[n + 1][k + 1];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= k && j <= i; j++){
localMax[j - 1][j] = Integer.MIN_VALUE;
localMax[i][j] = Math.max(localMax[i - 1][j], globalMax[i - 1][j - 1])
+ nums[i - 1];
if(i == j) globalMax[i][j] = localMax[i][j];
else globalMax[i][j] = Math.max(localMax[i][j], globalMax[i - 1][j]);
}
}
return globalMax[n][k];
}
}Reference
Last updated