Maximum Sum of 3 Non-Overlapping Subarrays

Maximum Sum of 3 Non-Overlapping Subarrays

A.題意

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的子數組使得子數組內元素和最大,然後返回值爲這三個子數組的開頭下標,當有多個解的時候返回下標最小的(字典序)

B.思路

這道題明顯是動態規劃的題目了,題目要求我們找三個數組,我們可以分別看成在三段裏面找到和最大的,我們用left[i]表示左邊所有數字裏面和最大的長度爲k的子數組的開頭下標,right[i]表示右邊所有數字裏面和最大的長度爲k的子數組的開頭下標,這樣我們動態規劃的思維就是遍歷所有可能的中間數組,找到和最大的就是問題的解,顯然中間數組的開頭下標範圍爲

k <= i <= n - 2*k

而對於left和right還有中間數組的和,這裏我們用了一個sum[i]來表示第i個數前所有數字之和來方便求三個子數組的和,使子數組求和操作變爲O(1),從而整一個問題複雜度變爲O(n)

C.代碼實現

class Solution {
public:
    vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> sum (n + 1,0);
        vector<int> left(n, 0);
        vector<int> right(n, 0);
        vector<int> ret (3, 0);
        for (int i = 0;i < n;i++)
        {
            sum[i + 1] = nums[i] + sum[i];
        }
        for (int i = k, total = sum[k] - sum[0];i < n;i++)
        {
            if (sum[i + 1] - sum[i + 1 - k] > total)
            {
                total = sum[i + 1] - sum[i + 1 - k];
                left[i] = i + 1 - k;
            }
            else {
                left[i] = left[i - 1];
            }
        }
        right[n - k] = n - k;
        for (int i = n - 1 - k,total = sum[n] - sum[n - k];i >= 0;i--)
        {
            if (sum[i + k] - sum[i] >= total)
            {
                total = sum[i + k] - sum[i];
                right[i] = i;
            }
            else {
                right[i] = right[i + 1];
            }
        }
        int max = 0;
        for (int i = k;i <= n - 2 * k;i++)
        {
            int le = left[i - 1], ri = right[i + k];
            int total = sum[le + k] - sum[le] + sum[ri + k] - sum[ri] + sum[i + k] - sum[i];
            if (total > max)
            {
                ret[0] = le;
                ret[1] = i;
                ret[2] = ri;
                max = total;
            } 
        }
        return ret;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章