[
math
greedy
]
BinarySearch 0291 Target Number with Operations
Problem statement
https://binarysearch.com/problems/Target-Number-with-Operations/
Solution
We need to go from the end. Be careful with cases like y = 10**10
and x = 10**10//2 + 1
, then we can not divide by 2
, but we need to subtract 1
a lot, in this case we can return steps + y - x
Complexity
It is O(log y)
for time and space.
Code
class Solution:
def solve(self, x, y):
steps = 0
while x != y:
if y % 2 == 0:
if y // 2 >= x:
y //= 2
else:
return steps + (y - x)
else:
y -= 1
steps += 1
return steps