41. Maximum Subarray

Description

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

The subarray should contain at least one number.

Example

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

Challenge

Can you do it in time complexity O(n)?

        这是一道求最大子串和的问题,想解决这个问题,我们需要考虑如下几种情况:

        情况一:加上一个正数——那自然最好了,求知不得嘛。且慢,假如前几个数的和为负数,突然来了个正数,是把正数加入旧的队列中,还是这个正数自立门户呢

啥意思?例如,有如此序列 -1,3,5。。。。等等,你是直接从3开始呢,还是把-1这个拖油瓶带着?很明显,为了保证整个子串的值最大,应该从3开始,该思路

对应于下面代码中的注释一。

        情况二:加上的数是一个负数——虽然说加上一个负数可能会变小,但有时候我们还是得加上的。例如:3,  4,  -5,  6, 7.......虽然加上-5会变小,但是它后面有更大的数,

能让整个序列得和变大。但有时候,加上了一个负数真的会使整个值变小,例如:3,-2,  1 我就三个数,加上-2后,哪怕再加上个一,相对于原来的3来说,还是变小了。

这个时候,就要求我们定义两个变量了,一个来保存最终的结果(res),另一个来“大胆地尝试”(curSum),如果一不小心curSum>res了,则更新res的值。代码如下:

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code here
        int curSum=0;
        int res=Integer.MIN_VALUE;
        for(int num:nums){
            curSum=Math.max(curSum+num,num);//注释一
            res=Math.max(curSum,res);
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9074054.html