package LeetCode_1031
/**
* 1031. Maximum Sum of Two Non-Overlapping Subarrays
* https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/
* Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays,
* which have lengths L and M.
* (For clarification, the L-length subarray could occur before or after the M-length subarray.)
Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) and either:
0 <= i < i + L - 1 < j < j + M - 1 < A.length,
or
0 <= j < j + M - 1 < i < i + L - 1 < A.length.
Example 1:
Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
Example 2:
Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
Example 3:
Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.
Note:
1. L >= 1
2. M >= 1
3. L + M <= A.length <= 1000
5. 0 <= A[i] <= 1000
* */
class Solution {
/*
* solution: prefix sum, keep tracking left range and right range for L,M and M,L,
* Time:O(n), Space:O(n)
* */
fun maxSumTwoNoOverlap(A: IntArray, L: Int, M: Int): Int {
if (A.isEmpty()) {
return 0
}
val n = A.size
val prefixSumArray = IntArray(n)
prefixSumArray[0] = A[0]
for (i in 1 until n) {
prefixSumArray[i] += prefixSumArray[i - 1] + A[i]
}
//the L-length sub-array could occur before or after the M-length sub-array
val maxLM = getMaxValue(prefixSumArray, L, M)
val maxML = getMaxValue(prefixSumArray, M, L)
return Math.max(maxLM, maxML)
}
private fun getMaxValue(nums: IntArray, leftSize: Int, rightSize: Int): Int {
val totalSize = leftSize + rightSize
var maxLeft = 0
var rightValue = 0
var maxValue = 0
/*
* calculate sum by L,M, for example: [3,8,1,3,2,1,8,9,0], L = 3, M = 2,
* size of array is 9, handle get sum from L before M processing:
* left range: 0-2, right range:3-4,
* left range: 1-3, right range:4-5,
* left range: 2-4, right range:5-6,
* left range: 3-5, right range:6-7,
* left range: 4-6, right range:7-8,
* */
for (i in totalSize - 1 until nums.size) {
//keep tracking left max value
maxLeft = Math.max(maxLeft, getRangeSum(nums, i - (totalSize - 1), i - rightSize))
/*
current right sum, no need to keeping the maximum right, because here is scan left to right,
would renew the rightValue, for example:[2,1,5,6,0,9,5,0,3,8], L = 4, M = 3,
will occur: [6,0,9,5], [0,3,8], [0,9,5], then [0,3,8] should be the right answer
*/
rightValue = getRangeSum(nums, i - (rightSize - 1), i)
maxValue = Math.max(maxValue, maxLeft + rightValue)
}
return maxValue
}
private fun getRangeSum(prefixSumArray: IntArray, start: Int, end: Int): Int {
if (start == 0) {
return prefixSumArray[end]
}
return prefixSumArray[end] - prefixSumArray[start - 1]
}
}