首页 > 其他 > 详细

【Leetcode】最大子序和

时间:2019-09-09 14:51:30      阅读:76      评论:0      收藏:0      [点我收藏+]

 

思路:

分治法。记最大子序和为maxResult,函数为int getMaxSub( *, * ) {}。

向量A= [a1, a2, a3, ...., ai, ai+1, a+2, ......, aj-1, aj],

maxResult = max( maxresult(a1, ......, ai),  getMaxSub(*, i+1) ),其中sum(a1, ......, ai) <= 0.

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if(nums.size() == 0)
            return -1;
        
        return getMaxSub(nums, 0);
    }
    
    int getMaxSub(const vector<int>& vecInt, int index) {
        
        int maxR = vecInt[index], sum = 0;
        
        for(index; index < vecInt.size(); ++index) {
            sum = sum + vecInt[index];
            
            if(sum <= 0 && index < (vecInt.size() - 1)) {  // 确保下一级序列非空
                maxR = max(maxR, getMaxSub(vecInt, index+1));
                return maxR;
            }
            else {
                maxR = max(maxR, sum);
            }
        }
        return maxR;
    }
};
执行用时 :12 ms, 在所有 C++ 提交中击败了64.15%的用户
内存消耗 :9.4 MB, 在所有 C++ 提交中击败了76.19%的用户

【Leetcode】最大子序和

原文:https://www.cnblogs.com/gdut-gordon/p/11491420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!