LeetCode 3479: Fruits Into Baskets III Solution
Master LeetCode problem 3479 (Fruits Into Baskets III), a medium 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.
3479. Fruits Into Baskets III
Problem Explanation
Explanation
To solve this problem, we can iterate through the fruits and baskets arrays and greedily assign each fruit to a basket with sufficient capacity. We can use a hashmap to keep track of the available baskets for each fruit type. If a fruit cannot be placed in any basket, we increment the count of unplaced fruits. Finally, we return the count of unplaced fruits.
Algorithm:
- Initialize a hashmap to store the available baskets for each fruit type.
- Iterate through the fruits array:
- For each fruit type, find the first available basket with sufficient capacity.
- If no basket is available, increment the count of unplaced fruits.
- Return the count of unplaced fruits.
Time Complexity: O(n) where n is the number of fruits (or baskets)
Space Complexity: O(n)
Solution Code
import java.util.HashMap;
class Solution {
public int unplacedFruits(int[] fruits, int[] baskets) {
HashMap<Integer, Integer> basketMap = new HashMap<>();
int unplacedCount = 0;
for (int i = 0; i < fruits.length; i++) {
int fruitType = fruits[i];
int basketIndex = -1;
for (int j = 0; j < baskets.length; j++) {
if (baskets[j] >= fruitType && (!basketMap.containsKey(fruitType) || basketMap.get(fruitType) < j)) {
basketIndex = j;
break;
}
}
if (basketIndex == -1) {
unplacedCount++;
} else {
basketMap.put(fruitType, basketIndex);
}
}
return unplacedCount;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3479 (Fruits Into Baskets III)?
This page provides optimized solutions for LeetCode problem 3479 (Fruits Into Baskets III) 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 3479 (Fruits Into Baskets III)?
The time complexity for LeetCode 3479 (Fruits Into Baskets III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3479 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3479 in Java, C++, or Python.