Problem · Array

Minimum Operations to Halve an Array Sum

Learn this problem
MediumGrab logoGrabNEW GRADPHONE SCREEN

Problem 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[]) → int

Examples

Example 1

values = [7,4,8,1]return = 3

The original sum is 20. Halving 8, then 7, then a current 4 reaches sum 10 in three operations.

Example 2

values = [10]return = 1

Replacing 10 by 5 reaches exactly half the original sum.

Constraints

  • 1 <= values.length <= 100000.
  • 1 <= values[i] <= 1000000000.

More Grab problems

drafts saved locally
public int minimumHalvingOperations(int[] values) {
    // Write your code here.
}
values[7,4,8,1]
expected3
checking account