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;
    }
}

 

Update:

public class Solution {
    public int maxSubArray(int[] nums) {
        int max = Integer.MIN_VALUE;
        if(nums == null || nums.length == 0)
            return max;
        int localMax = 0;
        
        for(int i = 0; i < nums.length; i++) {
            localMax += nums[i];
            max = Math.max(max, localMax);
            if(localMax < 0)
                localMax = 0;
        }
        
        return max;
    }
}

 

二刷:

Java:

Dynamic programming

Time Complexity - O(n), Space Complexity - O(1)

public class Solution {
    public int maxSubArray(int[] nums) {    //dp
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int globalMax = Integer.MIN_VALUE, localMax = 0;
        for (int i = 0; i < nums.length; i++) {
            localMax += nums[i];
            globalMax = Math.max(globalMax, localMax);
            if (localMax < 0) {
                localMax = 0;
            }
        }
        return globalMax;
    }
}

 

三刷:

这道题在Amazon电面二的时候问到过,不过不是返回最大值,而是返回subarray。这样的话我们要保存local和global的starting index以及length。 Follow up是overflow或者underflow该怎么处理, throw ArithmeticException就可以了。

Java:

public class Solution {
  public int maxSubArray(int[] nums) {
    if (nums == null || nums.length == 0) return 0;
    int globalMax = Integer.MIN_VALUE, localMax = 0;
    for (int i = 0; i < nums.length; i++) {
      localMax += nums[i];
      globalMax = Math.max(globalMax, localMax);
      if (localMax < 0) localMax = 0;
    }
    return globalMax;
  }
}

 

或者

public class Solution {
    public int maxSubArray(int[] nums) {
        int globalMax = Integer.MIN_VALUE;
        int localMax = 0;
        for (int i : nums) {
            localMax += i;
            globalMax = Math.max(globalMax, localMax);
            if (localMax < 0) localMax = 0;
        }
        return globalMax;
    }
}

 

posted @ 2015-04-17 23:39  YRB  阅读(776)  评论(0编辑  收藏  举报