Maximum Subarray
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
.
思路一:
不定长的滑动窗口,如果前面的sum值小于零了,说明对于之后的sum值计算产生减少的效果,所以此时将sum置0,每次都更新max值。
1 public int maxSubArray(int[] A) { 2 int sum = 0; 3 int max = Integer.MIN_VALUE; 4 for(int i=0; i<A.length; i++) { 5 sum += A[i]; 6 max = Math.max(max, sum); 7 sum = Math.max(sum, 0); 8 } 9 return max; 10 }