forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-number-of-operations-to-make-x-and-y-equal.py
56 lines (51 loc) · 1.38 KB
/
minimum-number-of-operations-to-make-x-and-y-equal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Time: O(x)
# Space: O(x)
# memoization
class Solution(object):
def minimumOperationsToMakeEqual(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
def memoization(x):
if y >= x:
return y-x
if x not in lookup:
lookup[x] = min(x-y, min(min(x%d, d-x%d)+memoization(x//d+int(d-x%d < x%d))+1 for d in (5, 11)))
return lookup[x]
lookup = {}
return memoization(x)
# Time: O(x)
# Space: O(x)
# bfs
class Solution2(object):
def minimumOperationsToMakeEqual(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
if y >= x:
return y-x
upper_bound = x+(x-y)
result = 0
lookup = {x}
q = [x]
while q:
new_q = []
for x in q:
if x == y:
return result
candidates = [x+1, x-1]
for d in (5, 11):
if x%d == 0:
candidates.append(x//d)
for new_x in candidates:
if not (0 <= new_x <= upper_bound and new_x not in lookup):
continue
lookup.add(new_x)
new_q.append(new_x)
q = new_q
result += 1
return -1