53. 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.

链接: http://leetcode.com/problems/maximum-subarray/

题解:求连续数组最大和。初始设置结果为Integer.MIN_VALUE,然后当前curMax小于0时重置其为0。 Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public int maxSubArray(int[] nums) {

        if(nums == null || nums.length == 0)

            return 0;

        int globalMax = Integer.MIN_VALUE, curMax = 0;

        

        for(int i = 0; i < nums.length; i++){

            curMax += nums[i];

            globalMax = Math.max(globalMax, curMax);

            if(curMax < 0)

                curMax = 0;

        }    

        

        return globalMax;

    }

}

 

测试:

你可能感兴趣的:(array)