<LeetCode> 题41:最大子数组

Description

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

The subarray should contain at least one number.

Have you met this question in a real interview?   Yes

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)?

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    int maxSubArray(vector<int> &nums) {
        // write your code here
        int max = nums.at(0);
        int sum =nums.at(0);
        for(int i =1;i<nums.size();i++){
        if(sum<0)
          sum = 0;
          sum += nums.at(i);
        if(max<sum)
          max = sum;
    }
    return max;
            }
};

这个题自己没有想出来,参考网友代码,理解思想后自己又加的。

为什么sum<0的时候要对sum赋0?

因为sum是存储某组连续元素的和,如果sum小于0:

sum+a[i]+...+a[n]肯定比a[i]+...+a[n]要小,因此直接舍弃前面的相加和,从接下来一项重新开始算

猜你喜欢

转载自blog.csdn.net/gulaixiangjuejue/article/details/80570417