leetcode:Maximum Subarray

1、

  Given an array of integers, find a contiguous subarray which has the largest sum.

      Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

2、

public static int maxSubArray(int[] A) {
        if (A == null || A.length == 0){
            return 0;
        }
        
        int max = Integer.MIN_VALUE, sum = 0;
        for (int i = 0; i < A.length; i++) {
            //sum:进行逐一加减
            sum += A[i];
            max = Math.max(max, sum);
            sum = Math.max(sum, 0);
        }

        return max;
    }
    
     public int maxSubArray2(int[] A) {
            if (A == null || A.length == 0){
                return 0;
            }
            int max = Integer.MIN_VALUE, sum = 0, minSum = 0;
            for (int i = 0; i < A.length; i++) {
                sum += A[i];
                max = Math.max(max, sum - minSum);
                minSum = Math.min(minSum, sum);
            }

            return max;
        }
工作小总结,有错请指出,谢谢。
原文地址:https://www.cnblogs.com/zilanghuo/p/5312087.html