#2944
Minimum Number of Coins for Fruits
MediumArrayDynamic ProgrammingQueueHeap (Priority Queue)Monotonic QueueDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
Using dynamic programming, we can build a solution that calculates the minimum coins needed to buy all fruits by considering the best fruit to buy at each step. This way, we avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array where dp[i] represents the minimum coins needed to buy fruits from index i to the end.
- 2Step 2: Iterate from the last fruit to the first fruit, calculating the minimum cost for each fruit based on previous results.
- 3Step 3: For each fruit, consider buying it and adding the cost of the next fruits that can be taken for free.
solution.py9 lines
1def minCoins(prices):
2 n = len(prices)
3 dp = [0] * n
4 dp[n - 1] = prices[n - 1]
5 for i in range(n - 2, -1, -1):
6 dp[i] = prices[i] + dp[i + 1]
7 for j in range(i + 1, n):
8 dp[i] = min(dp[i], prices[i] + dp[j])
9 return dp[0]ℹ
Complexity note: The time complexity remains O(n²) due to the nested loop structure, but we are storing results in the dp array to avoid redundant calculations. The space complexity is O(n) because we use an array to store the minimum costs.
- 1Dynamic programming helps in breaking down the problem into smaller subproblems.
- 2Choosing the right fruit to buy can lead to significant savings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.