Problem · Array
Minimum Operations to Halve an Array Sum
Learn this problemProblem statement
Given a nonempty array of positive integers values, one operation chooses one position and replaces its current value x with floor(x / 2).
Let originalSum be the sum before any operations and currentSum the sum afterward. Return the minimum number of operations needed until 2 * currentSum <= originalSum. The same position may be chosen more than once.
Function
minimumHalvingOperations(values: int[]) → intExamples
Example 1
values = [7,4,8,1]return = 3The original sum is 20. Halving 8, then 7, then a current 4 reaches sum 10 in three operations.
Example 2
values = [10]return = 1Replacing 10 by 5 reaches exactly half the original sum.
Constraints
1 <= values.length <= 100000.1 <= values[i] <= 1000000000.