Lintcode 最大子数组 II

本文介绍了一个算法问题,即寻找一个整数数组中两个不重叠的子数组,使它们的和达到最大值。子数组必须由连续元素组成,并且至少包含一个数。文章提供了基于贪心算法的解决方案,实现时间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个整数数组,找出两个 不重叠 子数组使得它们的和最大。
每个子数组的数字在数组中的位置应该是连续的。
返回最大的和。

 注意事项

子数组最少包含一个数

样例

给出数组 [1, 3, -1, 2, -1, 2]
这两个子数组分别为 [1, 3] 和 [2, -1, 2] 或者 [1, 3, -1, 2] 和 [2],它们的最大和都是 7

挑战 

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

标签 

贪心 枚举法 LintCode 版权所有 数组 子数组 前后遍历



这题的主要想法就是从前面和后面分别开始     如上篇“最大子数组” 一样计算出每一个节点为最后一个节点时的最大和并存入left和right数组,然后通过计算两个数组left[i]和right[i+1]最大的和即为所求。(为了用最大数组的结果写的比较乱)


class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: An integer denotes the sum of max two non-overlapping subarrays
     */
         void maxSubArray(vector<int> &nums,int first,int end,int flag,vector<int> &array) {
        // write your code here
        int sum=nums[first];
        int max=nums[first];
        int i;
        
        if(flag==1)
        i=first+1;
        else
        i=first-1;
        
        
        
        for(;flag==1?i<=end:i>=end;){
            if(sum<=0){
            sum=nums[i];
            }
            else
            sum+=nums[i];
            if(max<sum)
            max=sum;
  //         cout<<max<<endl;
            array.push_back(max);
            if(flag==1)
            i++;
            else
            i--;
            
        }
        
    }
    
    int maxTwoSubArrays(vector<int> nums) {
        // write your code here
        if(nums.empty())
        return 0;
        int n=nums.size();
        int max;
        int sum;
        vector<int> left,right;
        left.push_back(nums[0]);
        right.push_back(nums[n-1]);
        maxSubArray(nums,0,n-1,1,left);
        maxSubArray(nums,n-1,0,0,right);
       
        for(int i=0;i<n-1;i++){
           sum=left[i]+right[n-i-2];
            if(i==0)
              max=sum;
            else if(max<sum)
            max=sum;
            
        }
         return max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值