Problem · Array
Minimum Cost of Left and Right Propagation
Learn this problemProblem statement
You are given a positive integer array values. You may perform either propagation operation any number of times and in any order:
- Choose index
iand propagate left: replace every element beforeiwithvalues[i]. This costsi * values[i]. - Choose index
iand propagate right: replace every element afteriwithvalues[i]. This costs(n - 1 - i) * values[i].
Return the minimum total cost needed to make every array element equal. You may perform zero operations when the array is already uniform.
Function
minimumPropagationCost(values: int[]) → longExamples
Example 1
values = [5,2,4]return = 4Keep the middle value 2, propagate it left for cost 2, and propagate it right for another cost 2.
Example 2
values = [1,1,2,1]return = 2Keep the first run of two 1s and propagate right from index 1 for cost 2.
Constraints
1 <= values.length <= 1000001 <= values[i] <= 10^9- The answer fits in a signed 64-bit integer.