编程题:求数组中不重叠的两个子数组最大和


原题是 leetcode 1031 两个非重叠子数组的最大和 。

暴力方法的思路是确定其中一个子数组L的起始位置,计算当前该子数组的和,移动另一个子数R组,计算两个子数组和,然后移动L,再进行上述操作。时间复杂度会达到O(l*r*n*n),l r分别为两个子数组的长度。

优化思路,利用前缀和计算子数组的和,减小l*r的时间复杂度。在移动数组时,以右边数组的起始点索引作为循环索引,在这个循环索引变大的过程,左边子数组的可存在范围逐渐从左到右变大,可以利用之前的结果跟最新能覆盖到的长度为L的子数组和进行比较,得到左边子数组的最大和。

#include<vector>
#include<iostream>
using namespace std;
int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {
    int res = 0; // 函数返回值
    int temp = 0; // 位于左边的子数组最大和
    vector<int>pre_sum(nums.size() + 1); // 前缀和 
    for (int i = 1; i < nums.size() + 1; i++) {
        // pre_sum[i]表示的是nums[0] nums[1]到nums[i-1]相加的和
        pre_sum[i] += (pre_sum[i - 1] + nums[i - 1]);
    }
    // 长度为firstLen的数组在左边
    for (int i = firstLen; i + secondLen <= nums.size(); i++) {
        temp = max(temp, pre_sum[i] - pre_sum[i - firstLen]);
        res = max(res, temp + pre_sum[i + secondLen] - pre_sum[i]);
    }
    // 长度为secondLen的数组在左边
    temp = 0;
    for (int i = secondLen; i + firstLen <= nums.size(); i++) {
        temp = max(temp, pre_sum[i] - pre_sum[i - secondLen]);
        res = max(res, temp + pre_sum[i + firstLen] - pre_sum[i]);
    }
    return res;
}
int main() {
    int n;
    cin >> n;
    vector<int>nums(n);
    for (int i = 0; i < n; i++)cin >> nums[i];
    int l, r;
    cin >> l >> r;
    cout << maxSumTwoNoOverlap(nums, l, r) << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值