[leetcode] 689. Maximum Sum of 3 Non-Overlapping Subarrays

题目:

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).


思想:将k个元素看成一个整体来分析

代码:

class Solution {
public:
    vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
        int sum = 0;
        vector<int> ksum(nums.size()-k+1, 0);
        for(int i = 0; i < nums.size(); i++){
            sum += nums[i];
            if(i >= k) sum -= nums[i-k];
            if(i >= k-1) ksum[i-k+1] = sum;
        }
        
        int maxindex = 0;
        vector<int> left(ksum.size(), 0);
        for(int i = 0; i < ksum.size(); i++){
            if(ksum[i] > ksum[maxindex]) maxindex = i;
            left[i] = maxindex;
        }
        
        vector<int> right(ksum.size(), 0);
        maxindex = ksum.size() - 1;
        for(int i = ksum.size()-1; i >=0 ; i--){
            if(ksum[i] >= ksum[maxindex]) maxindex = i;
            right[i] = maxindex;
        }
        
        vector<int> a(3, -1);     
        for(int i = k; i < ksum.size() - k; i++){
            int leftmax = left[i-k];
            int rightmax = right[i+k];
            if(a[0] == -1 || ksum[leftmax] + ksum[rightmax]+ ksum[i] > ksum[a[0]] + ksum[a[1]] + ksum[a[2]]){
                a[0] = leftmax;
                a[1]= i;
                a[2] = rightmax;
            }
        }
        return a;
    }
};

猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/80828130
今日推荐