I need to write a function to calculate minimal sum of the local maximum of the subarrays of an array.
For example, we have an array [2, 3, 1, 4, 5, 6]
and the number of sub arrays is 3
. We want to get the min sum of the local max of the sub arrays. What that means is that, for example, one possible way to divide the current array into 3 sub arrays is [[2,3], [1], [4,5,6]]
and the local maxs for each subarray is 3, 1, 6
respectively. And the sum of the local maxs is 3 + 1 + 6 = 10
. For this particular array, [2, 3, 1, 4, 5, 6]
, this is the minimal sum of all its possible sub-array variations.
My approach is to first get all the possible sub-array variations for a given array. and get the min sum of them.
function getSubarrays(array, numOfSubarray) {
const results = []
const recurse = (index, subArrays) => {
if (index === array.length && subArrays.length === numOfSubarray) {
results.push([...subArrays])
return
}
if (index === array.length) return
// 1. push current item to the current subarray
// when the remaining items are more than the remaining sub arrays needed
if (array.length - index - 1 >= numOfSubarray - subArrays.length) {
recurse(
index + 1,
subArrays.slice(0, -1).concat([subArrays.at(-1).concat(array[index])])
)
}
// 2. start a new subarray when the current subarray is not empty
if (subArrays.at(-1).length !== 0)
recurse(index + 1, subArrays.concat([[array[index]]]))
}
recurse(0, [[]], 0)
return results
}
function getMinSum(arrays) {
return arrays.reduce(
(minSum, array) =>
Math.min(
minSum,
array.reduce((sum, subarray) => sum + Math.max(...subarray), 0)
),
Infinity
)
}
getMinSum(getSubarrays([[2,3], [1], [4,5,6]], 3)) // 10
However, I think the time complexity for my solution is really high. My guess is that it is on the order of 2^n
(feel free to correct me if I am wrong). I wonder if there is a more efficient way to calculate this.