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.
題意:求連續子數組的最大和html
public class Solution { public int maxSubArray(int[] nums) { int len=nums.length; if(nums==null || len==0)return 0; int MAX=nums[0]; int curSum=nums[0]; for(int i=1;i<len;i++){ if(curSum>0){ curSum+=nums[i]; }else{ curSum=nums[i]; } MAX=Math.max(curSum,MAX); } return MAX; } }
PS:第一種思路,逐漸累加循環。java
還有一種思路,能夠用動態規劃作。數組
public class Solution { public int maxSubArray(int[] nums) { int len=nums.length; if(nums==null || len==0)return 0; //dp[i]表明以nums[i]爲結尾的最大和。 int[] dp=new int[len]; dp[0]=nums[0]; int MAX=dp[0]; for(int i=1;i<len;i++){ if(dp[i-1]<0){ dp[i]=nums[i]; }else{ dp[i]=dp[i-1]+nums[i]; } MAX=Math.max(dp[i],MAX); } return MAX; } }