Minimum Moves to Reach Target Score - Problem

Imagine you're playing a strategic number-building game! ๐ŸŽฎ You start with the humble integer 1 and need to reach a target number using the most efficient strategy possible.

You have two types of moves available:

  • Increment: Add 1 to your current number (x = x + 1) - unlimited uses โž•
  • Double: Multiply your current number by 2 (x = 2 ร— x) - limited to maxDoubles uses only! โšก

Your mission is to find the minimum number of moves needed to transform 1 into your target number. Since doubling is more powerful but limited, you'll need to use it strategically!

Example: To reach target = 19 with maxDoubles = 2:
1 โ†’ 2 (double) โ†’ 4 (double) โ†’ 8 (increment) โ†’ 9 โ†’ ... โ†’ 19
Total: 17 moves

Input & Output

example_1.py โ€” Basic Case
$ Input: target = 5, maxDoubles = 0
โ€บ Output: 4
๐Ÿ’ก Note: Since we can't use any doubles, we must increment 4 times: 1 โ†’ 2 โ†’ 3 โ†’ 4 โ†’ 5. Total: 4 moves.
example_2.py โ€” Strategic Doubling
$ Input: target = 19, maxDoubles = 2
โ€บ Output: 7
๐Ÿ’ก Note: Optimal path: 1 โ†’ 2 (double) โ†’ 4 (double) โ†’ 8 โ†’ 9 โ†’ 10 โ†’ 11 โ†’ 12 โ†’ 13 โ†’ 14 โ†’ 15 โ†’ 16 โ†’ 17 โ†’ 18 โ†’ 19. But more efficient: working backwards gives us 7 moves total.
example_3.py โ€” Edge Case
$ Input: target = 1, maxDoubles = 3
โ€บ Output: 0
๐Ÿ’ก Note: We're already at the target! No moves needed.

Constraints

  • 1 โ‰ค target โ‰ค 109
  • 0 โ‰ค maxDoubles โ‰ค 100
  • Target is always reachable with given constraints

Visualization

Tap to expand
๐Ÿ”๏ธ Mountain Descent Strategy19Summit (Target)18Walk down9Express liftLIFT84LIFT1Base CampFinal descent4โ†’2โ†’1 (3 steps)๐Ÿง—โ€โ™€๏ธ Descent Rules๐Ÿšถโ€โ™‚๏ธ Odd altitude: Must walk down (-1)๐Ÿš  Even + lifts: Take express (รท2)๐Ÿšถโ€โ™‚๏ธ Even + no lifts: Walk remainingโœ… Total moves: 7 stepsโšก Time complexity: O(log n)๐Ÿ’พ Space complexity: O(1)Walk pathExpress lift
Understanding the Visualization
1
Start at Summit
Begin at the target altitude and plan your descent
2
Odd Heights โ†’ Walk
If you're at an odd height, you must have walked up the last step, so walk down
3
Even Heights โ†’ Lift Decision
If you're at an even height and have lift tickets, you probably took a lift to get there
4
No Lifts โ†’ Walk All
When out of lift tickets, you must walk the remaining distance
5
Reach Base
Count total steps taken to reach base camp (altitude 1)
Key Takeaway
๐ŸŽฏ Key Insight: Working backwards with greedy choices (walk down from odd heights, take lifts from even heights when available) gives us the optimal O(log n) solution!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.0K Views
High Frequency
~15 min Avg. Time
1.5K 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