
题意:如题,找出不相交的三个k元子数组,使得和最大,输出三个子数组的首项下标,若有多个答案,则取字典序最小的。
分析与思路:这道题是一道动态规划的题,思路不难想出,一层一层来解决,先用一个数组oneSubarray记录每个位置的数组和,即:oneSubarray[i]表示
sum(nums(i-k+1)~nums(i)),然后用twoSubarray[i]表示max(oneSubarray[k-1]~oneSubarray[i-k])+oneSubarray[i],同理threeSubarray[i]表示
max(twoSubarray[k*2-1]~twoSubarray[i-k])+oneSubarray[i],同时记录好对应的数组索引,最后的最大值就是出现过的最大threeSubarray。
代码:
typedef struct {
int a = 0;
int b = 0;
} twoPos;
typedef struct {
int a = 0;
int b = 0;
int c = 0;
} threePos;
class Solution {
public:
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
int *oneSubarray = new int[nums.size()];//记录以i结尾的子数组和
int *twoSubarray = new int[nums.size()];//记录i-k前的最大子数组与以i结尾的子数组的和
int *threeSubarry = new int[nums.size()];//记录i-k前的最大两数组和与以i结尾的子数组的和
int maxOne = 0,maxTwo = 0,maxThree = 0;//记录出现过的最大1,2,3个数组和的值
int first = k - 1, second = 2 * k - 1, third = 3 * k - 1;//出现过的最大一二三数组和的值
twoPos * twoPoss = new twoPos[nums.size()];//对应于twoSubarray的每个位置的两个子数组索引
threePos * threePoss = new threePos[nums.size()];//对应于threeSubarry的每个位置的三个子数组的索引
for (int i = k - 1; i < nums.size(); i++) {
oneSubarray[i] = 0;
for (int j = i - k + 1; j <= i; j++) {
oneSubarray[i] += nums[j];
}
if (i >= 2 * k - 1) {
if (maxOne < oneSubarray[i - k]) {
maxOne = oneSubarray[i - k];
first = i - k;
}
twoSubarray[i] = maxOne + oneSubarray[i];
twoPoss[i].a = first;
twoPoss[i].b = i;
}
if (i >= 3 * k - 1) {
if (maxTwo < twoSubarray[i - k]) {
maxTwo = twoSubarray[i - k];
second = i - k;
}
threeSubarry[i] = maxTwo + oneSubarray[i];
if (threeSubarry[i] > maxThree) {
maxThree = threeSubarry[i];
third = i;
threePoss[i].a = twoPoss[second].a;
threePoss[i].b = twoPoss[second].b;
threePoss[i].c = i;
}
}
}
vector<int> result;
result.push_back(threePoss[third].a - k + 1);
result.push_back(threePoss[third].b - k + 1);
result.push_back(threePoss[third].c - k + 1);
delete[] oneSubarray;
delete[] twoSubarray;
delete[] threeSubarry;
delete[] twoPoss;
delete[] threePoss;
return result;
}
};
本文介绍了一种利用动态规划求解给定数组中三个不相交子数组的最大和的方法,并给出了详细的实现步骤及代码示例。通过定义多个辅助数组记录中间结果,最终找到满足条件的三个子数组。
833

被折叠的 条评论
为什么被折叠?



