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
.
1 public class Solution { 2 public int maxSubArray(int[] A) { 3 int sum=A[0]; 4 int max=A[0]; 5 for (int i = 1; i < A.length; i++) { 6 if (sum<0) { 7 sum=A[i]; 8 }else { 9 sum=sum+A[i]; 10 } 11 12 if (max<sum) { 13 max=sum; 14 } 15 } 16 return max; 17 18 } 19 }