41.最大子数组

描述

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

子数组最少包含一个数

您在真实的面试中是否遇到过这个题?  

样例

给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

挑战

要求时间复杂度为O(n)

这道题是《数据结构》第一章中的例题,解法有很多,例如分治思想

而时间复杂度O(n)是一种讨巧的方法。

即申请一个变量储存最大值,将数组顺次相加与最大值比较并更新,若相加的得到的值小于等于0就抛弃这一段子数组,重新开始计数。注意存在全为负数的情况。

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 m_max=nums[0];
        int count=0;
        int i=0;
        
        for(;i<nums.size();i++){
            if(nums[i]<0) m_max=max(m_max,nums[i]);
            else break;
        }
        
        for(;i<nums.size();i++){
            count+=nums[i];
            if(count>m_max) m_max=count;
            if(count<0) count=0; 
        }
        
        return m_max;
    }
};

猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80350672