Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2969: Minimum Number of Coins for Fruits II

In this guide, we solve Leetcode #2969 Minimum Number of Coins for Fruits II in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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 ith fruit.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Queue, Array, Dynamic Programming, Monotonic Queue, Heap (Priority Queue)

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: prices = [3,1,2] Output: 4 Explanation: You can acquire the fruits as follows: - Purchase the 1st fruit with 3 coins, and you are allowed to take the 2nd fruit for free. - Purchase the 2nd fruit with 1 coin, and you are allowed to take the 3rd fruit for free. - Take the 3rd fruit for free. Note that even though you were allowed to take the 2nd 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.

Python Solution

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]

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy