Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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];
    }
};
posted on 2015-10-28 04:27  Tonix  阅读(171)  评论(0编辑  收藏  举报