您的位置:首页 > 其它

LintCode "Maximum Subarray III" !

2015-10-28 04:27 369 查看
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
[k];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: