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.

思路: 我们可以用一个array来记录走过的点的和, 这里我们的array起名叫curSum, 表示的是从某个点开始,累计走过的点的和。指针在走的过程中,我们要保证curSum中的和比较大。所以我们要比较前一个点的curSum是否大于0, 如果大于0,我们把前一个点的curSum加上当前点的值, 否则我们把当前点的值作为curSum。 因为要找出最大的subarray的和,我们需要维持一个global 的maxSum值。

public class Solution {
    public int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) 
            return Integer.MIN_VALUE;
        int curSum = nums[0];
        int maxSum = nums[0];
        for (int i = 1; i < nums.length; i++) {
            curSum = curSum > 0 ? curSum + nums[i]: nums[i];
            maxSum = Math.max(curSum, maxSum);
        return maxSum;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s