#2139

Minimum Moves to Reach Target Score

Medium
MathGreedyGreedyMathematical Optimization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of building up from 1 to the target, we can reverse the problem by starting at the target and working our way back to 1. This allows us to make more strategic decisions about when to double or decrement.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize moves to 0.
  2. 2Step 2: While target is greater than 1, check if target is even and maxDoubles is available.
  3. 3Step 3: If both conditions are met, halve the target and decrement maxDoubles. Otherwise, decrement the target by 1.
  4. 4Step 4: Increment the moves counter until target reaches 1.
solution.py13 lines
1# Full working Python code
2
3def minMoves(target, maxDoubles):
4    moves = 0
5    while target > 1:
6        if maxDoubles > 0 and target % 2 == 0:
7            target //= 2
8            maxDoubles -= 1
9        else:
10            target -= 1
11        moves += 1
12    return moves
13

Complexity note: The time complexity is O(log n) because each doubling operation effectively halves the target, leading to a logarithmic number of operations relative to the target value.

  • 1Using the doubling operation strategically can significantly reduce the number of moves needed.
  • 2Working backwards from the target allows for a more efficient approach, especially when the target is large.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.