Minimum Number of Coins for Fruits — LeetCode 2944 Python Solution

MediumQueueArrayDynamic ProgrammingMonotonic QueueHeap (Priority Queue)
Problem
#2944
Reading time
2 min

The problem

You are given an 0-indexed integer array prices where prices[i] denotes the number of coins needed to purchase the (i + 1)th fruit. The fruit market has the following reward for each fruit: If you purchase the (i + 1)th fruit at prices[i] coins, you can get any number of the next i fruits for free.

Python solution

Python
class Solution:
    def minimumCoins(self, prices: List[int]) -> int:
        @cache
        def dfs(i: int) -> int:
            if i * 2 >= len(prices):
                return prices[i - 1]
            return prices[i - 1] + min(dfs(j) for j in range(i + 1, i * 2 + 2))

        return dfs(1)

Complexity

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

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2944. Minimum Number of Coins for Fruits is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2944. Minimum Number of Coins for Fruits?
LeetCode 2944. Minimum Number of Coins for Fruits is rated Medium on LeetCode.
What is the time complexity of LeetCode 2944. Minimum Number of Coins for Fruits?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2944. Minimum Number of Coins for Fruits?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2944. Minimum Number of Coins for Fruits cover?
LeetCode 2944. Minimum Number of Coins for Fruits is tagged Queue, Array, Dynamic Programming, Monotonic Queue and Heap (Priority Queue) 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