Input: n =39Output: 3Explanation: We can do the following operations:- Add 20=1 to n, so now n =40.- Subtract 23=8 from n, so now n =32.- Subtract 25=32 from n, so now n =0.It can be shown that 3is the minimum number of operations we need to make n equal to 0.
Input: n =54Output: 3Explanation: We can do the following operations:- Add 21=2 to n, so now n =56.- Add 23=8 to n, so now n =64.- Subtract 26=64 from n, so now n =0.So the minimum number of operations is3.
The minimum number of operations is determined by how many bits need to be changed to zero, but sometimes flipping a bit can create a carry that reduces the total number of steps. The greedy approach tries both adding and subtracting powers of two at each bit position.
funcminOperations(nint) int {
dp:=map[int]int{}
vardfsfunc(int) intdfs = func(xint) int {
ifx==0 {
return0 }
ifv, ok:=dp[x]; ok {
returnv }
ans:=1<<30fori:=0; (1<<i) <=x*2; i++ {
p:=1<<it:=1+dfs(abs(x-p))
ift < ans {
ans = t }
}
dp[x] = ansreturnans }
returndfs(n)
}
funcabs(xint) int {
ifx < 0 {
return-x }
returnx}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
Map<Integer, Integer> dp =new HashMap<>();
publicintminOperations(int n) {
return dfs(n);
}
privateintdfs(int x) {
if (x == 0) return 0;
if (dp.containsKey(x)) return dp.get(x);
int ans = Integer.MAX_VALUE;
for (int i = 0; (1 << i) <= x * 2; i++) {
int p = 1 << i;
ans = Math.min(ans, 1 + dfs(Math.abs(x - p)));
}
dp.put(x, ans);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
privateval dp = mutableMapOf<Int, Int>()
funminOperations(n: Int): Int = dfs(n)
privatefundfs(x: Int): Int {
if (x ==0) return0 dp[x]?.let { returnit }
var ans = Int.MAX_VALUE
var i = 0while ((1 shl i) <= x * 2) {
val p = 1 shl i
ans = minOf(ans, 1 + dfs(kotlin.math.abs(x - p)))
i++ }
dp[x] = ans
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defminOperations(self, n: int) -> int:
dp: dict[int, int] = {}
defdfs(x: int) -> int:
if x ==0:
return0if x in dp:
return dp[x]
ans = float('inf')
i =0while (1<< i) <= x *2:
p =1<< i
ans = min(ans, 1+ dfs(abs(x - p)))
i +=1 dp[x] = ans
return ans
return dfs(n)
⏰ Time complexity: O(log n * log n) — For each bit position, we try both add/subtract, and memoization ensures each state is computed once. The recursion depth is up to log n.
🧺 Space complexity: O(log n) — The memoization table stores results for each possible value up to n, which is at most log n unique states.