标签:sub which example imu style ica ret max 动态规划
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
此题和Maximum product subarray很像,只不过比那个简单一点,也是用的动态规划做法做的,首先思考最优子结构性质,前面的最优解+当前数组值和当前数组值进行比较,取较大的值,直到求到全局解。重叠子问题也存在,将前面的最优解的值存放在了res里面,代码如下:
public class Solution {
public int maxSubArray(int[] nums) {
if(nums.length==0) return 0;
int res = nums[0];
int cur = nums[0];
for(int i=1;i<nums.length;i++){
cur = Math.max(cur+nums[i],nums[i]);
res = Math.max(cur,res);
}
return res;
}
}
标签:sub which example imu style ica ret max 动态规划
原文地址:http://www.cnblogs.com/codeskiller/p/6357438.html