AlgoLounge

Minimum Number of Coins for Fruits

medium

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^(th) fruit at prices[i] coins, you can get the next i fruits 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.

Examples

Example 1:

Input: prices = [3,1,2]
Output: 4
Explanation: 
- Purchase the 1st fruit with 3 coins, you are allowed to take the 2nd fruit for free.
- Purchase the 2nd fruit with 1 coin, you are allowed to take the 3rd fruit for free.
- Take the 3rd fruit for free.
It is possible to acquire all the fruits for 4 coins.

Example 2:

Input: prices = [1,10,1,1]
Output: 2
Explanation:
- Purchase the 1st fruit with 1 coin, you are allowed to take the 2nd fruit for free.
- Take the 2nd fruit for free.
- Purchase the 3rd fruit for 1 coin, you are allowed to take the 4th fruit for free.
- Take the 4th fruit for free.
It is possible to acquire all the fruits for 2 coins.

Constraints

  • 1 <= prices.length <= 1000
  • 1 <= prices[i] <= 10^5
TypeScript
Loading editor…
List of test cases (8)
Case 1
prices = [3,1,2]
Case 2
prices = [1,10,1,1]
Case 3
prices = [26,18,6,12,49,7,45,45]
Case 4
prices = [1]
Case 5
prices = [5,4,3]
Case 6
prices = [1,2,3,4,5]
Case 7
prices = [10,1,1,1]
Case 8
prices = [3,2,1]