Maximum Subarray III(最大子数组 III)

http://www.lintcode.com/en/problem/maximum-subarray-iii/?rand=true

package com.LintCode.MaximumSubarray3;


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
        int[][] singleMax = new int[k + 1][nums.length + 1];
//        表示j个数,i个子数组的最大和,必须包含第j个数
        int[][] max = new int[k + 1][nums.length + 1];
//        表示j个数,i个子数组的最大和,可以不包含第j个数
        for (int i = 1; i <= k; i++) {
//            要分成i个子数组,最小得有i个数
            singleMax[i][i - 1] = Integer.MIN_VALUE;
            for (int j = i; j <= nums.length; j++) {
//                包含第j个数的最大值,是它和前边一起组成始数组或者它单独成为子数组的大的那个
                singleMax[i][j] = Math.max(singleMax[i][j - 1], max[i - 1][j - 1]) + nums[j - 1];
                if (i == j) {
                    max[i][j] = singleMax[i][j];
                } else {
                    max[i][j] = Math.max(singleMax[i][j], max[i][j - 1]);
                }
            }
        }
        return max[k][nums.length];
    }
}

你可能感兴趣的:(Maximum Subarray III(最大子数组 III))