Maximum Subarray

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.

思路:

  不定长的滑动窗口,对于非负数对窗口有积极作用,对于负数,影响到窗口的正值了,窗口重新开始,没影响,窗口继续

我的代码:

public class Solution {

    public int maxSubArray(int[] A) {

        int max = Integer.MIN_VALUE;

        if(A == null || A.length == 0)  return max;

        int len = A.length;

        for(int i = 0; i < len; i++)

        {

            max = Math.max(A[i],max);

        }

        int curSum = 0;

        for(int i = 0; i < len; i++)

        {

            int cur = A[i];

            if( cur >= 0)

            {

                curSum += cur;

                max = Math.max(curSum,max);

            }

            else

            {

                if(curSum + cur < 0)    curSum = 0;

                else    curSum += cur;

            }

        }

        return max;

    }

}
View Code

别人代码:

public class Solution {

    public 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 += A[i];

            max = Math.max(max, sum);

            sum = Math.max(sum, 0);

        }



        return max;

    }

}
View Code

学习之处:

  别人的代码简介,但是不好理解

你可能感兴趣的:(array)