Leetcode 689. Maximum Sum of 3 Non-Overlapping Subarrays

Problem:

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

  这道题算是Hard题中的简单题了,思路也很明确,left[i]表示以小于等于i为开始位置的长度为k的最大子数组的起始位置,right[i]表示以大于等于i为开始位置的长度为k的最大子数组的起始位置。然后我们从中间的子数组开始遍历,根据left数组找到左侧的最大子数组起始位置,根据right数组找到右侧最大子数组起始位置,计算三个子数组之和即可。边界情况处理好就行了。

Code:

 

 1 class Solution {
 2 public:
 3     int getSum(vector<int> &sum,int start,int end){
 4         return sum[end+1]-sum[start];
 5     }
 6     vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
 7         int m = nums.size();
 8         vector<int> sum(m+1,0);
 9         for(int i = 0;i != m;++i){
10             sum[i+1] = sum[i]+nums[i];
11         }
12         vector<int> left(m-k+1);
13         int maximal = 0;
14         for(int i = k-1;i != m;++i){
15             int s = getSum(sum,i-k+1,i);
16             if(s > maximal){
17                 maximal = s;
18                 left[i-k+1] = i-k+1;
19             }
20             else
21                 left[i-k+1] = left[i-k];
22         }
23         vector<int> right(m-k+1);
24         maximal = 0;
25         for(int i = m-k;i >= 0;--i){
26             int s = getSum(sum,i,i+k-1);
27             if(s > maximal){
28                 maximal = s;
29                 right[i] = i;
30             }
31             else
32                 right[i] = right[i+1];
33         }
34         maximal = 0;
35         vector<int> result(3);
36         for(int i = k;i <= m-2*k;++i){
37             int l = left[i-k];
38             int r = right[i+k];
39             int s = getSum(sum,l,l+k-1)+getSum(sum,i,i+k-1)+getSum(sum,r,r+k-1);
40             if(s > maximal){
41                 maximal = s;
42                 result[0] = l;
43                 result[1] = i;
44                 result[2] = r;
45             }
46         }
47         return result;
48     }
49 };

 

posted on 2019-01-06 09:30  周浩炜  阅读(265)  评论(0编辑  收藏  举报

导航