Maximum Sum of 3 Non-Overlapping Subarrays

来源:互联网 发布:王士营养配餐软件 编辑:程序博客网 时间:2024/06/08 07:14

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;    }};
阅读全文
0 0
原创粉丝点击