首页 > 其他 > 详细

LintCode "Maximum Subarray III" !

时间:2015-10-28 06:59:50      阅读:217      评论:0      收藏:0      [点我收藏+]

Such a classic DP.. Thought flow:

1. find out the 2 vars in the problem statement: n and k

2. setup dp equation - my first thought was by n which was not natural, so by k.

3. details: if lower inx affects higher one, we calculate from higher to lower to avoid duplicate calculation.

class Solution {
public:
    /**
     * @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
     */
    int maxSubArray(vector<int> nums, int k) 
    {
        int n = nums.size();
        if (n < k) return 0;

        vector<vector<int>> dp(n + 1, vector<int>(k + 1, INT_MIN));

        //    Init with Group 0
        for(int i = 0; i <= n; i ++)
            dp[i][0] = 0;

        //    DP: from Group k-1 to Group k
        for (int sub = 1; sub <= k; sub++)     
        for (int i = sub; i <= nums.size(); i++) 
        {
            long long rsum = INT_MIN;
            long long csum = 0;
            
            //    NOTE: has to be from right to left - avoid duplicated calculation
            //          because dp[j][*] -> dp[i][*] where j < i
            for (int j = i - 1; j >= sub - 1; j--) 
            {
                csum = max((long long)nums[j], csum + nums[j]);
                rsum = max(rsum, csum);

                dp[i][sub] = max(dp[j][sub-1] + rsum, (long long)dp[i][sub]);
            }
        }
    
        return dp[n][k];
    }
};

LintCode "Maximum Subarray III" !

原文:http://www.cnblogs.com/tonix/p/4916194.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!