Skip to main content
Back to problems
#1558
Medium Algorithms

Minimum numbers of function calls to make target array

Array Greedy Bit Manipulation
62.8% acceptance
Feb 25, 2026
645
38
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 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>) -> i32 {
    // For each number, count the bits set (increments) + position of highest bit (doublings)
    // The doublings are shared across all numbers (we take the max highest bit)
    let mut ops = 0;
    let mut max_bits = 0;
    for n in nums {
      ops += n.count_ones() as i32; // number of +1 ops for this element
      let bits = 32 - n.leading_zeros() as i32; // highest bit position
      max_bits = max_bits.max(if n == 0 { 0 } else { bits - 1 }); // doublings needed
    }
    ops + max_bits
  }
}