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.
动态规划思路,d[i]为到以i结尾的子串的最大值,到i+1时,如果d[i] <= 0,d[i+1] = arr[i+1],否则d[i+1] = d[i] +arr[i+1]。发现每次计算只与前一个状态有关,那么久可以只设一个变量存放之前的结果。
public class Solution {
public int maxSubArray(int[] nums) {
if(nums.length ==0 || nums==null) return Integer.MIN_VALUE;
int pre = nums[0];
int res = nums[0];
for(int i = 1; i < nums.length; i++){
if(pre > 0){
pre += nums[i];
}else{
pre = nums[i];
}
res = Math.max(res, pre);
}
return res;
}
}
Top的方法思路也是如此,不过有一些还是开了一个数组,不值得。