Find the contiguous subarray within an array (containing at least one number) which have the largest sum. For example, given the array [ -2,1,-3,4,-1,2,1,-5,4],the contiguous subarray [4,-1,2,1] have the largest sum = 6.
Test instructions: To find the largest and most contiguous sub-arrays
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]; &nBsp; } max=math.max ( Cursum,max); } return max; }}
PS: The first way of thinking, gradually accumulate cycle.
There is also a way of thinking that can be done with dynamic planning.
Public class solution { public int maxsubarray (int[] nums ) { int len=nums.length; if (nums==null | | len==0) Return 0; //dp[i] represents the largest and at the end of 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; }}
Leetcode 53. Maximum Subarrayjava Language