Minimum Number of Operations to Make X and Y Equal Problem
Description
LeetCode Problem 2998.
You are given two positive integers x and y.
In one operation, you can do one of the four following operations:
- Divide
xby11ifxis a multiple of11. - Divide
xby5ifxis a multiple of5. - Decrement
xby1. - Increment
xby1.
Return the minimum number of operations required to make x and y equal.
Example 1:
Input: x = 26, y = 1
Output: 3
Explanation: We can make 26 equal to 1 by applying the following operations:
1. Decrement x by 1
2. Divide x by 5
3. Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
Example 2:
Input: x = 54, y = 2
Output: 4
Explanation: We can make 54 equal to 2 by applying the following operations:
1. Increment x by 1
2. Divide x by 11
3. Divide x by 5
4. Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
Example 3:
Input: x = 25, y = 30
Output: 5
Explanation: We can make 25 equal to 30 by applying the following operations:
1. Increment x by 1
2. Increment x by 1
3. Increment x by 1
4. Increment x by 1
5. Increment x by 1
It can be shown that 5 is the minimum number of operations required to make 25 equal to 30.
Constraints:
1 <= x, y <= 10^4
Solution
Approach: Memoized Search
If x <= y, the only option is to increment x, costing y - x. Otherwise there are two kinds of routes: decrement all the way down (cost x - y), or divide by 5 or by 11 at some point. Before dividing, we may need to get to a multiple, either by decrementing to the next lower multiple (x % 5 steps) or by incrementing to the next higher multiple (5 - x % 5 steps). Hence
dfs(x) = min(x - y, x % 5 + 1 + dfs(x / 5), 5 - x % 5 + 1 + dfs(x / 5 + 1), x % 11 + 1 + dfs(x / 11), 11 - x % 11 + 1 + dfs(x / 11 + 1))
and dfs(x) = y - x when x <= y. Each division shrinks x quickly, so there are few distinct states; memoize them.
Complexity: O(log x) distinct states, each O(1), so about O(log x) time and space.
from functools import lru_cache
class Solution:
def minimumOperationsToMakeEqual(self, x: int, y: int) -> int:
@lru_cache(None)
def dfs(x: int) -> int:
if y >= x:
return y - x
ans = x - y
ans = min(ans, x % 5 + 1 + dfs(x // 5))
ans = min(ans, 5 - x % 5 + 1 + dfs(x // 5 + 1))
ans = min(ans, x % 11 + 1 + dfs(x // 11))
ans = min(ans, 11 - x % 11 + 1 + dfs(x // 11 + 1))
return ans
return dfs(x)