Program to find minimum number of days to eat N oranges in Python

Suppose we have n oranges in the kitchen. We can eat some oranges every day following these rules:

  • Eat 1 orange

  • If n is even, eat n/2 oranges

  • If n is divisible by 3, eat 2*(n/3) oranges

We can select only one option each day. We need to find the minimum number of days to eat all n oranges.

Example Walkthrough

If the input is n = 10, the output will be 4 days ?

  • Day 1: Eat 1 orange, 10 − 1 = 9

  • Day 2: Eat 6 oranges (2*(9/3)), 9 − 6 = 3

  • Day 3: Eat 2 oranges (2*(3/3)), 3 − 2 = 1

  • Day 4: Eat the last orange, 1 − 1 = 0

Algorithm

We use dynamic programming with memoization to solve this problem efficiently ?

  • For each n, we have three choices but optimize by considering only n/2 and n/3 operations

  • Instead of eating 1 orange at a time, eat (n % 2) oranges to make n even, then apply n/2

  • Similarly, eat (n % 3) oranges to make n divisible by 3, then apply 2*(n/3)

  • Take minimum of both approaches

Implementation

def solve(n):
    def find_min_days(oranges):
        if oranges in memo:
            return memo[oranges]
        
        if oranges <= 2:
            return oranges
        
        # Option 1: Make n even, then eat n/2 oranges
        option1 = (oranges % 2) + 1 + find_min_days(oranges // 2)
        
        # Option 2: Make n divisible by 3, then eat 2*(n/3) oranges  
        option2 = (oranges % 3) + 1 + find_min_days(oranges // 3)
        
        memo[oranges] = min(option1, option2)
        return memo[oranges]
    
    memo = {}
    return find_min_days(n)

# Test the function
n = 10
result = solve(n)
print(f"Minimum days to eat {n} oranges: {result}")

n = 12
result = solve(n)
print(f"Minimum days to eat {n} oranges: {result}")
Minimum days to eat 10 oranges: 4
Minimum days to eat 12 oranges: 4

How It Works

The algorithm works by considering the most efficient eating strategies ?

  • Base case: If n ? 2, we need n days (eat 1 orange per day)

  • Recursive case: For larger n, we compare two strategies:

    • Eat (n % 2) oranges to make n even, then eat n/2 oranges the next day

    • Eat (n % 3) oranges to make n divisible by 3, then eat 2*(n/3) oranges the next day

  • Memoization: Store results to avoid recalculating the same subproblems

Time and Space Complexity

  • Time Complexity: O(log n) due to memoization and the fact that we divide n by 2 or 3 at each step

  • Space Complexity: O(log n) for the memoization table and recursion stack

Conclusion

This dynamic programming solution efficiently finds the minimum days to eat all oranges by choosing the optimal eating strategy at each step. The key insight is to make strategic moves to quickly reduce the number of oranges using division operations.

Updated on: 2026-03-26T14:10:10+05:30

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements