Minimum Number of Days to Eat N Oranges — LeetCode 1553 Python Solution

HardMemoizationDynamic Programming
Problem
#1553
Reading time
2 min

The 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.

Example

Input
n = 10
Output
4
Explanation
You have 10 oranges.

Python solution

Python
class Solution:
    def minDays(self, n: int) -> int:
        @cache
        def dfs(n: int) -> int:
            if n < 2:
                return n
            return 1 + min(n % 2 + dfs(n // 2), n % 3 + dfs(n // 3))

        return dfs(n)

Complexity

MeasureComplexity
TimeO(\log^2 n)
SpaceO(\log^2 n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1553. Minimum Number of Days to Eat N Oranges is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1553. Minimum Number of Days to Eat N Oranges?
LeetCode 1553. Minimum Number of Days to Eat N Oranges is rated Hard on LeetCode.
What is the time complexity of LeetCode 1553. Minimum Number of Days to Eat N Oranges?
The Python solution on this page runs in O(\log^2 n).
What is the space complexity of LeetCode 1553. Minimum Number of Days to Eat N Oranges?
The Python solution on this page uses O(\log^2 n) auxiliary space.
What topics does LeetCode 1553. Minimum Number of Days to Eat N Oranges cover?
LeetCode 1553. Minimum Number of Days to Eat N Oranges is tagged Memoization and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview