Minimum Moves to Reach Target Score — LeetCode 2139 Python Solution

MediumGreedyMath
Problem
#2139
Pattern
Greedy
Reading time
2 min

The problem

You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.

Example

Input
target = 5, maxDoubles = 0
Output
4
Explanation
Keep incrementing by 1 until you reach target.

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(\min(\log target, maxDoubles))
SpaceO(\min(\log target, maxDoubles)) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2139. Minimum Moves to Reach Target Score is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2139. Minimum Moves to Reach Target Score?
LeetCode 2139. Minimum Moves to Reach Target Score is rated Medium on LeetCode.
What is the time complexity of LeetCode 2139. Minimum Moves to Reach Target Score?
The Python solution on this page runs in O(\min(\log target, maxDoubles)).
What is the space complexity of LeetCode 2139. Minimum Moves to Reach Target Score?
The Python solution on this page uses O(\min(\log target, maxDoubles)) auxiliary space.
What topics does LeetCode 2139. Minimum Moves to Reach Target Score cover?
LeetCode 2139. Minimum Moves to Reach Target Score is tagged Greedy and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview