Input: prices =[3,1,2]Output: 4Explanation: You can acquire the fruits as follows:- Purchase the 1st fruit with3 coins, and you are allowed to take the 2nd fruit for free.- Purchase the 2nd fruit with1 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 4is the minimum number of coins needed to acquire all the fruits.
Example 2:
1
2
3
4
5
6
7
8
Input: prices =[1,10,1,1]Output: 2Explanation: You can acquire the fruits as follows:- Purchase the 1st fruit with1 coin, and you are allowed to take the 2nd fruit for free.- Take the 2nd fruit for free.- Purchase the 3rd fruit for1 coin, and you are allowed to take the 4th fruit for free.- Take the 4th fruit for free.It can be proven that 2is the minimum number of coins needed to acquire all the fruits.
To minimize coins, use DP where dp[i] is the minimum coins to buy up to fruit i. For each fruit, buying it lets us get the next i fruits for free, so we update the DP accordingly. A sliding window helps efficiently track the minimum cost for each range.