LeetCode-in-Java

2944. 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 ith fruit.

The fruit market has the following offer:

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.

Example 1:

Input: prices = [3,1,2]

Output: 4

Explanation: You can acquire the fruits as follows:

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 4 is the minimum number of coins needed to acquire all the fruits.

Example 2:

Input: prices = [1,10,1,1]

Output: 2

Explanation: You can acquire the fruits as follows:

It can be proven that 2 is the minimum number of coins needed to acquire all the fruits.

Constraints:

Solution

public class Solution {
    public int minimumCoins(int[] prices) {
        int n = prices.length;
        int[] dp = new int[n];
        dp[n - 1] = prices[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            int pos = i + 1;
            int acquired = i + pos;
            if (acquired + 1 < n) {
                int min = Integer.MAX_VALUE;
                for (int j = acquired + 1; j >= i + 1; j--) {
                    min = Math.min(min, dp[j]);
                }
                dp[i] = prices[i] + min;
            } else {
                dp[i] = prices[i];
            }
        }
        return dp[0];
    }
}