53. Maximum Subarray(動態規劃 求最大子數組)
阿新 • • 發佈:2018-04-05
lse pan int scrip mat rip pos 動態規劃 script
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 classSolution { 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 }
53. Maximum Subarray(動態規劃 求最大子數組)