Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
1. DP, but we only need to store adjacent 2 numbers.[−2,1,−3,4,−1,2,1,−5,4]
,the contiguous subarray
[4,−1,2,1]
has the largest sum = 6
.public class Solution { public int maxSubArray(int[] nums) { int len = nums.length; if(0 == len) return 0; int pre = nums[0]; int max = nums[0]; for(int i = 1; i < len; ++i){ if(pre < 0) pre = nums[i]; else pre = nums[i] + pre; max = Math.max(max, pre); } return max; } }
No comments:
Post a Comment