题目描述:
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.
Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example:
Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
Note:
nums.length will be between 1 and 20000.
nums[i] will be between 1 and 65535.
k will be between 1 and floor(nums.length / 3).
将数组拆分成3个不重叠的子数组,满足子数组和最大。任意一个子数组和可以根据前缀和在O(1)的时间内求得,如果枚举三个子数组起点,那么时间复杂度是O(n^3),但是如果能维护一个left数组,其中left[i]是一个pair表示下标i之前的最大子数组的起点和子数组和,同样维护一个right数组,其中right[i]是一个pair表示下标i之后的最大子数组的起点和子数组和,那么可以枚举中间子数组的起点,可以以O(1)的时间得到左右两个最大子数组的起点,因此整体的时间复杂度是O(n)。
class Solution {
public:
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
int n=nums.size();
vector<int> prefix_sum(n,0);
prefix_sum[0]=nums[0];
for(int i=1; i<n; i++)
prefix_sum[i]=prefix_sum[i-1] + nums[i];
vector<pair<int,int>> left(n,pair<int,int>(0,0));
int left_max=0;
for(int i=k-1; i<n; i++)
{
int cur_sum=0;
if(i==k-1) cur_sum=prefix_sum[k-1];
else cur_sum=prefix_sum[i]-prefix_sum[i-k];
if(cur_sum>left_max)
{
left_max=cur_sum;
left[i]=pair<int,int>(i-k+1,left_max);
}
else left[i]=left[i-1];
}
vector<pair<int,int>> right(n,pair<int,int>(0,0));
int right_max=0;
for(int i=n-k; i>=0; i--)
{
int cur_sum=0;
if(i==0) cur_sum=prefix_sum[k-1];
else cur_sum=prefix_sum[i+k-1]-prefix_sum[i-1];
if(cur_sum>right_max)
{
right_max=cur_sum;
right[i]=pair<int,int>(i,right_max);
}
else right[i]=right[i+1];
}
int sum=0;
vector<int> result(3,0);
for(int i=k; i<=n-2*k; i++)
{
int sum1=prefix_sum[i+k-1]-prefix_sum[i-1];
pair<int,int> pair1=left[i-1];
pair<int,int> pair2=right[i+k];
if(sum1+pair1.second+pair2.second>sum)
{
sum=sum1+pair1.second+pair2.second;
result[0]=pair1.first;
result[1]=i;
result[2]=pair2.first;
}
}
return result;
}
};