Fewest steps to one
Standard · Write code · about 12 min
Start from a positive integer n. In one step you may subtract 1, divide by 2 if the number is even, or divide by 3 if it is divisible by 3. Return the fewest steps that reach 1.
Dividing whenever possible is not always best: from 10, halving gives 10 → 5 → 4 → 2 → 1 (4 steps), but 10 → 9 → 3 → 1 takes 3.
Example 1
Input:
[10]
Output:
3
10 − 1 = 9, 9 / 3 = 3, 3 / 3 = 1.
Example 2
Input:
[7]
Output:
3
7 → 6 → 2 → 1.
Constraints
- 1 ≤ n ≤ 600
Learn the idea first: Overlapping subproblems and memoization, a visual lesson.
More Overlapping subproblems and memoization problems
- Memoized Fibonacci Warm-up
- Calls with and without memo Warm-up
- Which calls hit the cache Standard
- Climbing stairs with a memo Standard
- Memoized grid paths Challenge