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
.
递归方程;
dp[i] = dp[i-1]+nums[i] ,dp[i-1]>0
dp[i] = nums[i] ,else
1 class Solution { 2 public int maxSubArray(int[] nums) { 3 int dp[] = new int[nums.length+1]; 4 int max = nums[0]; 5 dp[0] = nums[0]; 6 for(int i =1;i<nums.length;i++){ 7 if(dp[i-1]<=0) 8 dp[i] = nums[i]; 9 else 10 dp[i] = dp[i-1]+nums[i]; 11 max = Math.max(dp[i],max); 12 } 13 return max; 14 } 15 }