498. Minimize Total Weight After Halving Operations
Minimize Total Weight After Halving Operations

You are given a list of integers weights, where weights[i] is the weight of the i-th item, and an integer operations.

In one halving operation, you choose any item and replace its weight w with floor(w / 2), i.e. integer division that rounds down. The same item can be chosen in more than one operation.

Perform exactly operations halving operations to minimize the total weight of all items, and return this minimum total weight.

Method Signature

long minimizeTotalWeight(List<Integer> weights, int operations)
  • weights: weights[i] is the current weight of the i-th item.
  • operations: the exact number of halving operations to perform.
  • Returns the minimum possible sum of all weights after all halving operations are done.

Constraints

  • 1 ≤ weights.size() ≤ 100,000
  • 1 ≤ weights[i] ≤ 1,000,000,000
  • 1 ≤ operations ≤ 100,000

Examples

Example 1

minimizeTotalWeight(weights = [4, 9, 16, 3], operations = 3)

Output: 15

  • Halve 16 to 8: [4, 9, 8, 3]
  • Halve 9 to 4: [4, 4, 8, 3]
  • Halve 8 to 4: [4, 4, 4, 3]
  • Total weight = 4 + 4 + 4 + 3 = 15.

Example 2

minimizeTotalWeight(weights = [7], operations = 5)

Output: 0

  • The only item is halved every time: 7 to 3, 3 to 1, 1 to 0, 0 to 0, 0 to 0.
  • A weight of 0 stays 0 when halved, so the total weight is 0.

Example 3

minimizeTotalWeight(weights = [25, 30, 11], operations = 4)

Output: 24

  • Halve 30 to 15: [25, 15, 11]
  • Halve 25 to 12: [12, 15, 11]
  • Halve 15 to 7: [12, 7, 11]
  • Halve 12 to 6: [6, 7, 11]
  • Total weight = 6 + 7 + 11 = 24.


Please use Laptop/Desktop or any other large screen to add/edit code.