#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.解题思路
采用滑动窗口确定第一块之后在剩余的列表中选取第二块得到遍历得到结果。