In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. Each subarray would be is of size k, and we want to maximize the sum of all3*k entries. Return The result asA list of indices representing the starting position of each interval (0-indexed).
If There is multiple answers,returnThe lexicographically smallest one. Example:input: [1,2,1,2,6,7,5,1],2Output: [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 'll be between1and20000. Nums[i] 'll be between1and65535. K 'll be between1and Floor (Nums.length/3).
The question asks for three non-overlapping intervals with maximum sum of all 3 intervals. If the middle interval is [I, i+k-1], where K-<= i <= n-2k, the left interval have to being in subrange [0, i-1], and th e right interval are from Subrange [I+k, n-1].
So the following solution are based on DP.
Then we test every possible starting index of middle interval, i.e. K <= i <= n-2k, and we can get the corresponding Left and right Max sum intervals easily from DP. And the run time is O (n).
Caution. In order to get lexicographical smallest order, when there is intervals with equal Max sum, always select the left Mo St One. So in the code, the IF condition is ' >= tot ' for right interval due to backward searching, and ' > tot ' for left inte Rval.
Class Solution {public int[] maxsumofthreesubarrays (int[] nums, int k) {int n = nums.length, maxsum = 0; int[] sum = new Int[n+1], posleft = new Int[n], posright = new Int[n], ans = new int[3]; for (int i = 0; i < n; i++) sum[i+1] = sum[i]+nums[i]; DP for starting index of the "left Max" sum interval for (int i = k, tot = sum[k]-sum[0]; i < n; i++) { if (Sum[i+1]-sum[i+1-k] > Tot) {posleft[i] = i+1-k; tot = Sum[i+1]-sum[i+1-k]; } else Posleft[i] = posleft[i-1]; }//DP for starting index of the right Max sum interval//Caution:the condition are ">= tot" for right I Nterval, and "> tot" for left interval posright[n-k] = n-k; for (int i = n-k-1, tot = sum[n]-sum[n-k]; I >= 0; i--) {if (Sum[i+k]-sum[i] >= tot) {PO Sright[i] = i; tot = Sum[i+k]-sum[i]; }else posright[i] = posright[i+1]; }//Test all possible middle interval for (int i = k; I <= n-2*k; i++) {int L = posleft[i-1] , r = Posright[i+k]; int tot = (Sum[i+k]-sum[i]) + (Sum[l+k]-sum[l]) + (sum[r+k]-sum[r]); if (Tot > maxsum) {maxsum = tot; Ans[0] = l; ANS[1] = i; ANS[2] = r; }} return ans; }}
689. Maximum Sum of 3 non-overlapping subarrays