LeetCode 2969: Minimum Number of Coins for Fruits II Solution

Master LeetCode problem 2969 (Minimum Number of Coins for Fruits II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2969. Minimum Number of Coins for Fruits II

Problem Explanation

Explanation:

To solve this problem, we can use a sliding window technique. We maintain a window that contains the maximum number of fruits allowed and slide the window to find the minimum number of coins needed to satisfy the condition. We keep track of the count of each type of fruit in the current window and adjust the window boundaries accordingly.

  1. Initialize variables left and right to represent the window boundaries.
  2. Iterate through the fruits array using the right pointer.
  3. Increment the count of the current fruit type in the window.
  4. If the window size exceeds the maximum number of fruits allowed, move the left pointer to shrink the window until it satisfies the condition.
  5. Update the minimum number of coins needed as we slide the window.
  6. Continue this process until reaching the end of the fruits array.

:

Solution Code

class Solution {
    public int minNumberOfCoins(int[] fruits, int maxFruits) {
        int[] count = new int[fruits.length];
        int left = 0, right = 0, types = 0, minCoins = Integer.MAX_VALUE;

        while (right < fruits.length) {
            if (count[fruits[right]] == 0) {
                types++;
            }
            count[fruits[right]]++;
            
            while (types > maxFruits) {
                count[fruits[left]]--;
                if (count[fruits[left]] == 0) {
                    types--;
                }
                left++;
            }

            minCoins = Math.min(minCoins, right - left + 1);
            right++;
        }

        return minCoins == Integer.MAX_VALUE ? -1 : minCoins;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2969 (Minimum Number of Coins for Fruits II)?

This page provides optimized solutions for LeetCode problem 2969 (Minimum Number of Coins for Fruits II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2969 (Minimum Number of Coins for Fruits II)?

The time complexity for LeetCode 2969 (Minimum Number of Coins for Fruits II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2969 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2969 in Java, C++, or Python.

Back to LeetCode Solutions