If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
分析:
因为这里不要求返回数组下标,可以通过一趟遍历来把所有元素相加,当和小于0的时候,舍弃之前所有。
这里是一个O(n)的解法。
public class Solution { public int maxSubArray(int[] A) { int sum = 0; int maxSum = Integer.MIN_VALUE; for(int i=0; i<A.length; i++){ sum += A[i]; maxSum = Math.max(maxSum, sum); if(sum < 0) sum=0; } return maxSum; } }