Imagine you're shopping at an exotic fruit market where the vendor has an incredible offer! Each fruit comes with a special deal: when you buy the i-th fruit for prices[i] coins, you get the next i fruits completely free!
You're given a 1-indexed array prices where prices[i] represents the cost of the i-th fruit. Here's the twist: even if you can take a fruit for free, you can still choose to purchase it to unlock a new offer for subsequent fruits.
Goal: Find the minimum number of coins needed to acquire all fruits from the market.
Example: If prices = [3, 1, 2], buying fruit 1 for 3 coins gives you fruits 2 and 3 for free, costing only 3 coins total. Alternatively, buying fruit 2 for 1 coin gives you fruit 3 for free, then you'd need 3 coins for fruit 1, totaling 4 coins. The optimal choice is 3 coins!
Input & Output
Visualization
Time & Space Complexity
Each element is added and removed from deque at most once, making it linear
DP array of size n plus deque storing at most n elements
Constraints
- 1 โค prices.length โค 105
- 1 โค prices[i] โค 109
- The array is 1-indexed in the problem description but 0-indexed in implementation