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 has the [4,−1,2,1] largest sum = 6 .
The problem is to ask for the maximum substring and
Must be O (n) of Time and O (1) of space
is to add each time, 1, first to determine whether it is all non-positive, if so, then directly return the largest number.
2, and then add a number each time, then add in turn, if NUMS[J] is greater than 0, then compared with the result of large.
2, if at this time and less than 0, then leave, and I will be placed at this time the next bit of J.
public class Solution {public int maxsubarray (int[] nums) {if (nums.length = = 1) return nums[0]; int result = Nums[0],ans = Nums[0]; int i = 0,J = 1; for (int k = 0;k<nums.length;k++) {if (Result < nums[k]) result = Nums[k]; } if (Result <= 0) return result; while (I<nums.length && J < nums.length) {if (Nums[i] < 0) {while (i<nums. Length && nums[i]<0) i++; if (i<nums.length) ans = nums[i]; j = i+1; } else if (Nums[j] >= 0) {ans+=nums[j]; j + +; result = result>ans?result:ans; }else{if (Ans+nums[j] <= 0) {i = j+1; j = j+2; if (i<nums.length) ans = nums[i]; }else{Ans+=nums[j]; j + +; }}} return result; }}
Then found to be in the writing is verbose. In fact, the following can
public class Solution {public int maxsubarray (int[] nums) { int max=nums[0]; for (int i=1;i<nums.length;++i) { nums[i]=nums[i-1]<0? Nums[i]: nums[i-1]+nums[i]; max = Math.max (max, nums[i]); } return max;} }
public class Solution {public int maxsubarray (int[] nums) {if (nums.length = = 1) return nums[0];int presum = Nums[0];i NT max = nums[0];for (int i = 1; i < nums.length; i++) {if (presum <= 0) presum = nums[i];else {presum + = Nums[i];} if (Presum > Max) max = Presum;} return Max;}}
Leetcode Maximum Subarray-----java