Minimum Number of Days to Eat N Oranges Problem
Description
LeetCode Problem 1553.
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
nis divisible by2then you can eatn / 2oranges. - If the number of remaining oranges
nis divisible by3then you can eat2 * (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.
Example 1:
Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange, 10 - 1 = 9.
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1.
Day 4: Eat the last orange 1 - 1 = 0.
You need at least 4 days to eat the 10 oranges.
Example 2:
Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange 1 - 1 = 0.
You need at least 3 days to eat the 6 oranges.
Constraints:
1 <= n <= 2 * 10^9
Solution
Approach: Memoized Recursion on Divisions
With n up to 2 * 109, a DP table over every count is out of the question. The key observation is that eating one orange at a time is only useful to reach a multiple of 2 or of 3, after which a big division follows. Eating single oranges for longer than that is never better. For an even n, eating two oranges and then halving takes three days to reach n / 2 - 1, while halving first and then eating one orange gets there in two.
So from n, there are only two sensible plans:
- Eat
n % 2single oranges, then halve:n % 2 + 1 + days(n / 2). - Eat
n % 3single oranges, then take two thirds:n % 3 + 1 + days(n / 3).
days(n) is the smaller of the two, with days(0) = 0 and days(1) = 1. Every state has the form n / (2^a * 3^b) (rounded down), so there are only about log2(n) * log3(n) of them, and a hash map memo makes each one computed once. The recursion depth is about log2(n), which is tiny.
Complexity: O(log2 n) time and O(log2 n) extra space for the memo.
from functools import lru_cache
class Solution:
def minDays(self, n: int) -> int:
@lru_cache(None)
def days(k: int) -> int:
if k < 2:
return k
# Eat single oranges until k is divisible by 2 (or 3), then halve (or cut to a third).
return 1 + min(k % 2 + days(k // 2), k % 3 + days(k // 3))
return days(n)