Input: prices =[3,1,2]Output: 4Explanation:
* Purchase the 1st fruit with`prices[0] = 3` coins, you are allowed to take the 2nd fruit for free.* Purchase the 2nd fruit with`prices[1] = 1` coin, you are allowed to take the 3rd fruit for free.* Take the 3rd fruit for free.Note that even though you could take the 2nd fruit for free as a reward of
buying 1st fruit, you purchase it to receive its reward, which is more
optimal.
Input: prices =[1,10,1,1]Output: 2Explanation:
* Purchase the 1st fruit with`prices[0] = 1` coin, you are allowed to take the 2nd fruit for free.* Take the 2nd fruit for free.* Purchase the 3rd fruit for`prices[2] = 1` coin, you are allowed to take the 4th fruit for free.* Take the 4th fruit for free.
Input: prices =[26,18,6,12,49,7,45,45]Output: 39Explanation:
* Purchase the 1st fruit with`prices[0] = 26` coin, you are allowed to take the 2nd fruit for free.* Take the 2nd fruit for free.* Purchase the 3rd fruit for`prices[2] = 6` coin, you are allowed to take the 4th,5th and 6th(the next three) fruits for free.* Take the 4th fruit for free.* Take the 5th fruit for free.* Purchase the 6th fruit with`prices[5] = 7` coin, you are allowed to take the 8th and 9th fruit for free.* Take the 7th fruit for free.* Take the 8th fruit for free.Note that even though you could take the 6th fruit for free as a reward of
buying 3rd fruit, you purchase it to receive its reward, which is more
optimal.
To minimize coins, we 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 monotonic queue can optimize the range updates.