Minimum Number of Days to Eat N Oranges - Problem

There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:

  • Eat one orange.
  • If the number of remaining oranges n is divisible by 2, then you can eat n / 2 oranges.
  • If the number of remaining oranges n is divisible by 3, then you can eat 2 * (n / 3) oranges.

You can only choose one of the actions per day.

Given the integer n, return the minimum number of days to eat n oranges.

Input & Output

Example 1 — Small Number
$ Input: n = 10
Output: 4
💡 Note: Day 1: eat 1 orange (9 remaining). Day 2: 9%3=0, eat 2*(9/3)=6 oranges (3 remaining). Day 3: 3%3=0, eat 2*(3/3)=2 oranges (1 remaining). Day 4: eat 1 orange (0 remaining). Total: 4 days.
Example 2 — Perfect Division
$ Input: n = 6
Output: 3
💡 Note: Day 1: 6%2=0, eat 6/2=3 oranges (3 remaining). Day 2: 3%3=0, eat 2*(3/3)=2 oranges (1 remaining). Day 3: eat 1 orange (0 remaining). Total: 3 days.
Example 3 — Base Case
$ Input: n = 1
Output: 1
💡 Note: Day 1: eat 1 orange (0 remaining). Total: 1 day.

Constraints

  • 1 ≤ n ≤ 2 × 109

Visualization

Tap to expand
Minimum Days to Eat N Oranges INPUT 10 n = 10 oranges Three Choices Per Day: 1. Eat 1 orange 2. If n%2=0: eat n/2 3. If n%3=0: eat 2*(n/3) n = 10 ALGORITHM STEPS 1 Start: n=10 10%2=0, eat 5 --> n=5 2 n=5, not divisible Eat 1 --> n=4 3 n=4, divisible by 2 Eat 2 --> n=2 4 n=2, divisible by 2 Eat 1 --> n=1 5 n=1, eat last Eat 1 --> n=0 (DONE) Optimal Path: 10-->5-->4-->2-->1-->0 Memoization caches results FINAL RESULT Days to eat all oranges: Day 1 10-->5 Day 2 5-->4 Day 3 4-->2 Day 4 2-->1 Done! 1-->0 Minimum Days: 4 Output: 4 Total oranges eaten: 5+1+2+1+1 = 10 [OK] Key Insight: Smart Path Selection with Memoization: Instead of trying all paths, prioritize division operations (n/2 or n/3) as they reduce n exponentially. Only subtract 1 to reach a number divisible by 2 or 3. This reduces time complexity from O(n) to O(log n) with memoization storing previously computed minimum days. TutorialsPoint - Minimum Number of Days to Eat N Oranges | Optimized Memoization (Smart Path Selection)
Asked in
Google 45 Microsoft 32 Amazon 28 Facebook 21
42.0K Views
Medium Frequency
~25 min Avg. Time
892 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