Minimum Numbers of Function Calls to Make Target Array Problem
Description
LeetCode Problem 1558.
You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:

You want to use the modify function to convert arr to nums using the minimum number of calls.
Return the minimum number of function calls to make nums from arr.
The test cases are generated so that the answer fits in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.
Example 2:
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.
Example 3:
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Count Bits
Read each target value in binary. Building v from 0 with "add one" and "double" is like writing its binary digits from the most significant one: doubling shifts every number left by one bit, and adding one sets the lowest bit.
- Increments act on one element at a time, and each
1bit ofvneeds its own increment, so the increments total the number of1bits over all numbers. - Doublings act on the whole array at once, so they are shared. The largest number needs
bitLength(max) - 1doublings to move its top bit into place, and every smaller number fits its own bits into the same doublings by doing its increments at the right moments.
The answer is the sum of the two. The tricky case is an all-zero array: no increments, and also no doublings (not -1), so the answer is 0.
Complexity: O(n log M) time with a bit loop (or O(n) with a builtin popcount), where M is the largest value, and O(1) extra space.
class Solution:
def minOperations(self, nums: List[int]) -> int:
# One increment per 1-bit of every number ...
increments = sum(bin(v).count("1") for v in nums)
# ... plus the doublings, shared by all numbers: enough to shift the largest one's top bit into place.
doublings = max(0, max(nums).bit_length() - 1)
return increments + doublings