LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays

实践是知识的母亲,知识是生活的明灯。这篇文章主要讲述LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays相关的知识,希望能为你提供帮助。
原题链接在这里:https://leetcode.com/problems/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).
题解:
Get the accumlated sum for nums.
Iterate from left to right to get the starting index of biggest subarray left to current index.
Iterate from right to left to get the starting index of biggest subarray right to current index.
Then for the middle part, index could be [k, n-2*k]. Iterate each of them, get the left biggest starting index and right biggest starting index. 
Keep updating the global maximum and res.
Time Complexity: O(n). n = nums.length.
Space: O(n).
AC java:
1 class Solution { 2public int[] maxSumOfThreeSubarrays(int[] nums, int k) { 3int [] res = new int[3]; 4Arrays.fill(res, -1); 5if(nums == null || nums.length < 3 * k){ 6return res; 7} 8 9int n = nums.length; 10int [] sum = new int[n+1]; 11for(int i = 0; i< n; i++){ 12sum[i+1] = sum[i] + nums[i]; 13} 14 15int [] leftPo = new int[n]; 16for(int i = k, max = sum[k] - sum[0]; i< n; i++){ 17if(sum[i+1] - sum[i+1-k] > max){ 18max = sum[i+1] - sum[i+1-k]; 19leftPo[i] = i+1-k; 20}else{ 21leftPo[i] = leftPo[i-1]; 22} 23} 24 25int [] rightPo = new int[n]; 26rightPo[n-k] = n-k; 27for(int i = n-k-1, max = sum[n] - sum[n-k]; i> =0; i--){ 28if(sum[i+k] - sum[i] > = max){ 29max = sum[i+k] - sum[i]; 30rightPo[i] = i; 31}else{ 32rightPo[i] = rightPo[i+1]; 33} 34} 35 36for(int i = k, max = 0; i< =n-2*k; i++){ 37int l = leftPo[i - 1]; 38int r = rightPo[i + k]; 39if(sum[i+k] - sum[i] + sum[l+k] - sum[l] + sum[r+k] - sum[r] > max){ 40max = sum[i+k] - sum[i] + sum[l+k] - sum[l] + sum[r+k] - sum[r]; 41res[0] = l; 42res[1] = i; 43res[2] = r; 44} 45} 46 47return res; 48} 49 }

【LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays】类似Best Time to Buy and Sell Stock III.

    推荐阅读