Problem Statement
You are given an integer array arr[]. Initially, another array of the same size contains only 0s.
You can perform only two types of operations:
Increment any one element by 1.
Double all elements of the array simultaneously.
Your task is to determine the minimum number of operations required to transform the initial all-zero array into the given array.
Examples
Example 1
Input
arr = [16, 16, 16]
Output
7
Explanation
[0,0,0]
→ [1,1,1] (3 increment operations)
→ [2,2,2] (1 double)
→ [4,4,4] (1 double)
→ [8,8,8] (1 double)
→ [16,16,16] (1 double)
Total = 3 + 4 = 7
Example 2
Input
arr = [2,3]
Output
4
Explanation
[0,0]
→ [1,1] (2 increments)
→ [2,2] (1 double)
→ [2,3] (1 increment)
Total = 4
Observation
Instead of thinking from 0 → target, think in reverse:
Target → 0
Reverse the operations:
Increment becomes decrement by 1.
Double becomes divide every element by 2.
This reverse approach reveals two important observations.
Observation 1: Odd Numbers Require a Decrement
Whenever a number is odd, it could not have been obtained by doubling.
Therefore, the last operation for that number must have been an increment.
For example:
7 → 6
5 → 4
3 → 2
Every odd value requires one decrement.
The total number of such decrements equals the number of set bits (1s) in the binary representation of every number.
Example
13 = 1101
Set bits = 3
This means 13 requires exactly 3 increment operations.
Java provides this directly using:
Integer.bitCount(num);
Observation 2: Doubling Affects the Entire Array
A doubling operation affects every element simultaneously.
Therefore, we only care about the maximum number of doublings required by any element.
For example:
16
1 → 2 → 4 → 8 → 16
It requires 4 doublings.
Similarly:
8 → 3 doublings
4 → 2 doublings
2 → 1 doubling
1 → 0 doublings
The answer is simply the maximum doubling count among all elements.
Algorithm
For every element:
Count its set bits.
Count how many times it can be divided by
2before becoming1.Keep the maximum division count.
Return:
Total Increments + Maximum Doublings
Complete Code
class Solution {
public int countMinOperations(int arr[]) {
int increments = 0;
int doubles = 0;
for (int num : arr) {
// Count increment operations
increments += Integer.bitCount(num);
// Count required doubles
int bits = 0;
while (num > 1) {
num >>= 1;
bits++;
}
doubles = Math.max(doubles, bits);
}
return increments + doubles;
}
}
Code Explanation
Step 1
int increments = 0;
int doubles = 0;
incrementsstores the total number of increment operations.doublesstores the maximum number of doubling operations required.
Step 2
for (int num : arr)

Join the conversation! Your thoughts help the community grow.