Minimum Moves to Reach Target Score Problem
Description
LeetCode Problem 2139.
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.
In one move, you can either:
- Increment the current integer by one (i.e.,
x = x + 1). - Double the current integer (i.e.,
x = 2 * x).
You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.
Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.
Example 1:
Input: target = 5, maxDoubles = 0
Output: 4
Explanation: Keep incrementing by 1 until you reach target.
Example 2:
Input: target = 19, maxDoubles = 2
Output: 7
Explanation: Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19
Example 3:
Input: target = 10, maxDoubles = 4
Output: 4
Explanation: Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10
Constraints:
1 <= target <= 10^90 <= maxDoubles <= 100
Solution
Approach: Work Backwards + Greedy
Go from target back to 1, since undoing a doubling is only possible on even numbers and it is always best to halve when allowed.
- If
target == 1, nothing is needed. - If no doublings are left, subtract 1 repeatedly:
target - 1moves. - If
targetis even and a doubling is left, spend one move to halve it and use up a doubling. - If
targetis odd, spend one move to subtract 1.
The recursion depth is about min(log target, maxDoubles) before the remaining decrements are counted in one step; it can also be written as a loop.
Time O(min(log target, maxDoubles)), space the same for the recursion.
class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
if target == 1:
return 0
if maxDoubles == 0:
return target - 1
if target % 2 == 0 and maxDoubles:
return 1 + self.minMoves(target >> 1, maxDoubles - 1)
return 1 + self.minMoves(target - 1, maxDoubles)