499非重叠子数组的最大和

#include <vector>
#include <iostream>
using namespace std;
int sum_vector(const vector<int>& nums, int start, int len){
    int sum = 0;
    for(int i = start;i <= start + len - 1; i++){
        sum += nums[i];
    }
    return sum;
}

int solution(vector<int> nums, int firstLen, int secondLen) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
    // write code here
    int ans;
    for(int i = 0; i < nums.size() - firstLen + 1; i++){
        int firstLensum = sum_vector(nums, i, firstLen);
        int secondLensum = 0;
        for(int j = i + firstLen; j <= nums.size() - secondLen; j++){
            secondLensum = max(secondLensum, sum_vector(nums, j, secondLen));
        } //第一段之后取

        for(int j = 0;j <= i - secondLen; j++){
            secondLensum = max(secondLensum, sum_vector(nums, j, secondLen));
        } //第一段之前取
        ans = max(ans, firstLensum + secondLensum);
    }
    return ans;
}

int main() {
    cout << (solution(vector<int>{0,6,5,2,2,5,1,9,4}, 1, 2) == 20) << endl;
    cout << (solution(vector<int>{3,8,1,3,5,2,1,0}, 3, 2) == 21) << endl;
    cout << (solution(vector<int>{2,1,4,3,5,9,5,0,3,8}, 4, 3) == 33) << endl;
    return 0;
}

1.问题描述

小R遇到一个数组 nums,他需要从中找到两个非重叠的子数组,它们的长度分别为 firstLen 和 secondLen。这两个子数组可以相互独立,顺序没有限制,但它们不能有任何重叠。你需要帮小R找出这些子数组的最大和。

2.解题思路

采用滑动窗口确定第一块之后在剩余的列表中选取第二块得到遍历得到结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值