![]() |
VOOZH | about |
Given a 1-indexed array prices[], where prices[i] represents the cost of the ith fruit in a store. The store has a special offer: if you buy the ith fruit for prices[i] coins, you can get the next i fruit for free.
Note: Even if you can get an fruit j for free, you still have the option to purchase it for prices[j] coins to receive a new offer. The task is to return the minimum number of coins needed to acquire all the fruits.
Input: prices = [30, 10, 20]
Output: 40
Explanation:
- Purchase the 1st fruit with 30 coins. Now, you are allowed to take the 2nd fruit for free, total coins = 30
- Purchase the 2nd fruit with 1 coin. Now, you are allowed to take the 3rd fruit for free, total coins = 30 + 10 = 40.
- Take the 3rd fruit for free, total coins = 40.
Input: prices = [2, 20, 2, 2]
Output: 4
Explanation:
- Purchase the 1st fruit with 1 coin. Now, you are allowed to take the 2nd fruit for free, total cost = 2.
- Take the 2nd fruit for free, total cost = 2.
- Purchase the 3rd fruit for 1 coin. Now, you are allowed to take the 4th fruit for free, total cost = 2 + 2.
- Take the 4th fruit for free, total cost = 4.
Approach: To solve the problem, follow the below idea:
The idea is to use the "take" and "nottake" approach of DP with memoization. When we take the ith fruit , we directly consider moving to fruits from i+1 to 2*i+2, skipping the next i fruits as per the offer. We recursively explore each valid move from these indices and find the minimum cost. Add the price of the current fruit to this minimum cost and return it. To optimize, we use a memoization vector initialized to zero to store the results of subproblems, ensuring we do not recompute values, improving efficiency.
Below is the implementation of the above algorithm:
40 4
Time Complexity: O(n), where n is the number of fruits in the fruit market.
Auxiliary Space: O(n)