[英]maximum subarray iii (from lintcode) dynamic programming solution
Can anyone walk me through this solution below? 谁能指导我完成下面的解决方案? What does p mean? p是什么意思? why its range j-1 to i? 为什么范围j-1到i? Thanks Given an array of integers and a number k, find k non-overlapping subarrays which have the largest sum. 感谢给定一个整数数组和一个数字k,找到具有最大和的k个非重叠子数组。
The number in each subarray should be contiguous. 每个子数组中的数字应该是连续的。
Return the largest sum. 返回最大和。
according to this blog( http://www.cnblogs.com/lishiblog/p/4183917.html ), the DP analysis is 根据此博客( http://www.cnblogs.com/lishiblog/p/4183917.html),DP分析是
DP. DP。 d[i][j] means the maximum sum we can get by selecting j subarrays from the first i elements. d [i] [j]表示我们可以通过从前i个元素中选择j个子数组来获得最大和。
d[i][j] = max{d[p][j-1]+maxSubArray(p+1,i)} d [i] [j] = max {d [p] [j-1] + maxSubArray(p + 1,i)}
we iterate p from i-1 to j-1, so we can record the max subarray we get at current p, this value can be used to calculate the max subarray from p-1 to i when p becomes p-1. 我们将p从i-1迭代到j-1,因此我们可以记录在当前p处获得的max子数组,当p变为p-1时,该值可用于计算从p-1到i的max子数组。
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(ArrayList<Integer> nums, int k) {
if (nums.size()<k) return 0;
int len = nums.size();
//d[i][j]: select j subarrays from the first i elements, the max sum we can get.
int[][] d = new int[len+1][k+1];
for (int i=0;i<=len;i++) d[i][0] = 0;
for (int j=1;j<=k;j++)
for (int i=j;i<=len;i++){
d[i][j] = Integer.MIN_VALUE;
//Initial value of endMax and max should be taken care very very carefully.
int endMax = 0;
int max = Integer.MIN_VALUE;
for (int p=i-1;p>=j-1;p--){
endMax = Math.max(nums.get(p), endMax+nums.get(p));
max = Math.max(endMax,max);
if (d[i][j]<d[p][j-1]+max)
d[i][j] = d[p][j-1]+max;
}
}
return d[len][k];
}
} }
What does p mean: just a iterator. p是什么意思:只是一个迭代器。 (Chinese Algorithm Coder always like short name for variable...) (中文算法编码器始终喜欢变量的简称...)
Why its range j-1 to i: 为什么范围j-1到i:
Indeed, dp analysis should be: 确实,dp分析应为:
d[i][j] = max{d[p][j-1]+maxSubArray(p+1,i)} j-1 <= p <= i-1 d [i] [j] = max {d [p] [j-1] + maxSubArray(p + 1,i)} j-1 <= p <= i-1
Why must p >= j-1 ? 为什么p> = j-1 ? Because as dp[i][j] define: 因为作为dp [i] [j]定义:
d[i][j] means the maximum sum we can get by selecting j subarrays from the first i elements. d [i] [j]表示我们可以通过从前i个元素中选择j个子数组来获得最大和。
You know , we can't select j sub-array without non-overlapping from j-1 elements. 要知道,如果没有j-1个元素的不重叠 ,我们就不能选择j个子数组。 That is to say, dp[i][j] make sense when i >= j. 也就是说,当i> = j时,dp [i] [j]是有意义的。
Any question, leave a comment here. 如有任何疑问,请在此处发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.