Minimum Moves to Reach Target Score - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: target = 5, maxDoubles = 0
Output: 4
💡 Note: Since we can't double, we need 4 increment operations: 1→2→3→4→5
Example 2 — Using Doubles
$ Input: target = 19, maxDoubles = 2
Output: 7
💡 Note: Optimal path working backwards: 19→18→9→8→4→2→1, total 6 moves. Forward: 1→2→4→8→9→18→19
Example 3 — Large Target
$ Input: target = 1000000000, maxDoubles = 30
Output: 39
💡 Note: Use doubles optimally by working backwards, then calculate remaining increments

Constraints

  • 1 ≤ target ≤ 109
  • 0 ≤ maxDoubles ≤ 31

Visualization

Tap to expand
Minimum Moves to Reach Target Score INPUT Game: 1 --> target 1 Start 5 Target Operations: x = x + 1 (increment) x = 2 * x (double) target 5 maxDoubles 0 No doubles allowed! ALGORITHM STEPS (Greedy - Reverse Approach) 1 Start from target Work backwards: 5 --> 1 2 Check maxDoubles maxDoubles = 0, no halving 3 Only decrement Subtract 1 each step 4 Count moves moves = target - 1 Trace (Reverse): 5 -1 4 -1 3 -1 2 -1 1 (Done!) FINAL RESULT Forward Path: 1 +1 2 +1 3 +1 4 +1 5 Target! Output: 4 [OK] 4 increments 0 doubles used Key Insight: Work BACKWARDS from target! If maxDoubles > 0 and target is even, halve it (reverse of double). Otherwise decrement. When maxDoubles=0, answer is simply (target - 1) since only +1 is available. TutorialsPoint - Minimum Moves to Reach Target Score | Greedy (Reverse Approach)
Asked in
Microsoft 15 Google 12 Amazon 8
32.0K Views
Medium Frequency
~15 min Avg. Time
896 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen