|
21 | 21 | */
|
22 | 22 | public class _689 {
|
23 | 23 | public static class Solution1 {
|
| 24 | + /**we basically need to find the interval (i, i+k-1) as the middle interval, where k <= i <= n-2k |
| 25 | + * then this interval (0, i-1) will be the left interval |
| 26 | + * the interval (i+k, n-1) will be the right interval. |
| 27 | + * |
| 28 | + * Please pay special attention to the variable name I use here: this `k` is not a random one, it's the `k` |
| 29 | + * from the passed in parameter. |
| 30 | + * |
| 31 | + * Credit: https://discuss.leetcode.com/topic/105577/c-java-dp-with-explanation-o-n/*/ |
24 | 32 | public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
|
| 33 | + if (nums == null || nums.length == 0) { |
| 34 | + return new int[]{}; |
| 35 | + } |
| 36 | + int n = nums.length; |
| 37 | + int[] sums = new int[n + 1]; |
| 38 | + for (int i = 0; i < n; i++) { |
| 39 | + sums[i + 1] = sums[i] + nums[i]; |
| 40 | + } |
25 | 41 |
|
26 |
| - return new int[]{}; |
| 42 | + int[] leftMax = new int[n]; |
| 43 | + for (int i = k, total = sums[k] - sums[0]; i < n; i++) { |
| 44 | + if (sums[i + 1] - sums[i + 1 - k] > total) { |
| 45 | + leftMax[i] = i + 1 - k; |
| 46 | + total = sums[i + 1] - sums[i + 1 - k]; |
| 47 | + } else { |
| 48 | + leftMax[i] = leftMax[i - 1]; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + int[] rightMax = new int[n]; |
| 53 | + rightMax[n - k] = n - k; |
| 54 | + for (int i = n - k - 1, total = sums[n] - sums[n - k]; i >= 0; i--) { |
| 55 | + if (sums[i + k] - sums[i] >= total) { |
| 56 | + rightMax[i] = i; |
| 57 | + total = sums[i + k] - sums[i]; |
| 58 | + } else { |
| 59 | + rightMax[i] = rightMax[i + 1]; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + //try to find all possible middle intervals |
| 64 | + int[] result = new int[3]; |
| 65 | + int max = 0; |
| 66 | + for (int i = k; i <= n - 2 * k; i++) { |
| 67 | + int left = leftMax[i - 1]; |
| 68 | + int right = rightMax[i + k]; |
| 69 | + int total = (sums[i + k] - sums[i]) + (sums[left + k] - sums[left]) + (sums[right + k] - sums[right]); |
| 70 | + if (total > max) { |
| 71 | + max = total; |
| 72 | + result[0] = left; |
| 73 | + result[1] = i; |
| 74 | + result[2] = right; |
| 75 | + } |
| 76 | + } |
| 77 | + return result; |
27 | 78 | }
|
28 | 79 | }
|
| 80 | + |
| 81 | + public static class Solution2 { |
| 82 | + /**reference: https://leetcode.com/articles/maximum-sum-of-3-non-overlapping-intervals*/ |
| 83 | + } |
29 | 84 | }
|
0 commit comments