Integer Replacement LeetCode solution in Python
1# Runtime: 42 ms (Top 77.23%) | Memory: 14 MB (Top 29.19%)234class Solution:5def integerReplacement(self, n: int) -> int:6dp = {}78def dfs(num):9if num == 1:10return 01112if num in dp:13return dp[num]1415# if num is even, we have only one option -> n / 216even = odd = 017if num % 2 == 0:18even = 1 + dfs(num // 2)19else:20# if num is odd, we have two option, either we increment the num or decrement the num21odd1 = 1 + dfs(num - 1)22odd2 = 1 + dfs(num + 1)23# take the min of both operation24odd = min(odd1, odd2)2526dp[num] = even + odd27return dp[num]2829return dfs(n)