Minimum Number of Coins for Fruits II Problem
Description
LeetCode Problem 2969.
You are at a fruit market with different types of exotic fruits on display.
You are given a 1-indexed array prices, where prices[i] denotes the number of coins needed to purchase the i^th fruit.
The fruit market has the following offer:
- If you purchase the
i^thfruit atprices[i]coins, you can get the nextifruits for free.
Note that even if you can take fruit j for free, you can still purchase it for prices[j] coins to receive a new offer.
Return the minimum number of coins needed to acquire all the fruits.
Example 1:
Input: prices = [3,1,2]
Output: 4
Explanation: You can acquire the fruits as follows:
- Purchase the 1^st fruit with 3 coins, and you are allowed to take the 2^nd fruit for free.
- Purchase the 2^nd fruit with 1 coin, and you are allowed to take the 3^rd fruit for free.
- Take the 3^rd fruit for free.
Note that even though you were allowed to take the 2^nd fruit for free, you purchased it because it is more optimal.
It can be proven that 4 is the minimum number of coins needed to acquire all the fruits.
Example 2:
Input: prices = [1,10,1,1]
Output: 2
Explanation: You can acquire the fruits as follows:
- Purchase the 1^st fruit with 1 coin, and you are allowed to take the 2^nd fruit for free.
- Take the 2^nd fruit for free.
- Purchase the 3^rd fruit for 1 coin, and you are allowed to take the 4^th fruit for free.
- Take the 4^th fruit for free.
It can be proven that 2 is the minimum number of coins needed to acquire all the fruits.
Constraints:
1 <= prices.length <= 10^51 <= prices[i] <= 10^5
Solution
Approach: Dynamic Programming + Monotonic Queue
Let f[i] be the minimum number of coins needed to buy all fruits starting from fruit i; the answer is f[1]. Buying fruit i gives fruits i+1 .. 2i for free, so the next fruit bought is some j with i + 1 <= j <= 2i + 1:
f[i] = prices[i - 1] + min(f[i + 1], ..., f[2i + 1])
and f[i] = prices[i - 1] when 2i >= n. Computing the minimum directly gives O(n^2), too slow for n = 10^5.
Going from i = n down to 1, the window [i + 1, 2i + 1] only shrinks at the right end and moves left, so it is a sliding window minimum. Keep a monotonic queue of indices: drop the front while it is beyond 2i + 1, read the minimum from the front, then drop from the back every index whose value is at least f[i] and push i. The values are stored back into prices to save space.
The time complexity is O(n) and the space complexity is O(n), where n is the length of prices.
from collections import deque
class Solution:
def minimumCoins(self, prices: List[int]) -> int:
n = len(prices)
q = deque()
for i in range(n, 0, -1):
while q and q[0] > i * 2 + 1:
q.popleft()
if i <= (n - 1) // 2:
prices[i - 1] += prices[q[0] - 1]
while q and prices[q[-1] - 1] >= prices[i - 1]:
q.pop()
q.append(i)
return prices[0]