Skip to content

1558. Minimum Numbers of Function Calls to Make Target Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  int minOperations(vector<int>& nums) {
    const int mx = ranges::max(nums);
    return accumulate(nums.begin(), nums.end(), 0, [](int acc, unsigned num) {
      return acc + popcount(num);
    }) + (mx == 0 ? 0 : static_cast<int>(log2(mx)));
  }
};
1
2
3
4
5
6
7
class Solution {
  public int minOperations(int[] nums) {
    final int mx = Arrays.stream(nums).max().getAsInt();
    return Arrays.stream(nums).map(num -> Integer.bitCount(num)).sum() +
        (mx == 0 ? 0 : (int) (Math.log(mx) / Math.log(2)));
  }
}
1
2
3
4
5
class Solution:
  def minOperations(self, nums: list[int]) -> int:
    mx = max(nums)
    return (sum(num.bit_count() for num in nums) +
            (0 if mx == 0 else mx.bit_length() - 1))