Intuition:
The problem can be solved by recursively reducing n to 1, always choosing the operation that leads to the minimum steps. For even numbers, divide by 2. For odd numbers, try both n+1 and n-1 and pick the minimum. Memoization avoids redundant calculations.
Approach:
If n is 1, return 0 (base case).
If n is even, recursively call with n/2.
If n is odd, recursively call with both n+1 and n-1, take the minimum.
Use a cache (memoization) to store results for each n to avoid recomputation.
classSolution {
privateval memo = mutableMapOf<Long, Int>()
funintegerReplacement(n: Int): Int {
return helper(n.toLong())
}
privatefunhelper(n: Long): Int {
if (n ==1L) return0 memo[n]?.let { returnit }
val ans = if (n % 2==0L) {
1 + helper(n / 2)
} else {
1 + minOf(helper(n + 1), helper(n - 1))
}
memo[n] = ans
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defintegerReplacement(self, n: int) -> int:
memo: dict[int, int] = {}
defhelper(x: int) -> int:
if x ==1:
return0if x in memo:
return memo[x]
if x %2==0:
ans =1+ helper(x //2)
else:
ans =1+ min(helper(x +1), helper(x -1))
memo[x] = ans
return ans
return helper(n)