|
| 1 | +/** |
| 2 | + * 3479. Fruits Into Baskets III |
| 3 | + * https://leetcode.com/problems/fruits-into-baskets-iii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i] |
| 7 | + * represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of |
| 8 | + * the jth basket. |
| 9 | + * |
| 10 | + * From left to right, place the fruits according to these rules: |
| 11 | + * - Each fruit type must be placed in the leftmost available basket with a capacity greater |
| 12 | + * than or equal to the quantity of that fruit type. |
| 13 | + * - Each basket can hold only one type of fruit. |
| 14 | + * - If a fruit type cannot be placed in any basket, it remains unplaced. |
| 15 | + * |
| 16 | + * Return the number of fruit types that remain unplaced after all possible allocations are made. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} fruits |
| 21 | + * @param {number[]} baskets |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var numOfUnplacedFruits = function(fruits, baskets) { |
| 25 | + const n = fruits.length; |
| 26 | + const bucketSize = Math.ceil(Math.sqrt(n)); |
| 27 | + const buckets = Array.from({ length: bucketSize }, () => []); |
| 28 | + |
| 29 | + for (let i = 0; i < baskets.length; i++) { |
| 30 | + const bucketIndex = Math.floor(i / bucketSize); |
| 31 | + buckets[bucketIndex].push([baskets[i], i]); |
| 32 | + } |
| 33 | + |
| 34 | + for (const bucket of buckets) { |
| 35 | + bucket.sort((a, b) => a[0] - b[0]); |
| 36 | + } |
| 37 | + |
| 38 | + let result = 0; |
| 39 | + for (const fruitQuantity of fruits) { |
| 40 | + let placed = false; |
| 41 | + |
| 42 | + for (const bucket of buckets) { |
| 43 | + if (bucket.length > 0 && bucket[bucket.length - 1][0] >= fruitQuantity) { |
| 44 | + let chosenIndex = -1; |
| 45 | + let minBasketIndex = Infinity; |
| 46 | + |
| 47 | + for (let i = 0; i < bucket.length; i++) { |
| 48 | + if (bucket[i][0] >= fruitQuantity && bucket[i][1] < minBasketIndex) { |
| 49 | + chosenIndex = i; |
| 50 | + minBasketIndex = bucket[i][1]; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if (chosenIndex !== -1) { |
| 55 | + bucket.splice(chosenIndex, 1); |
| 56 | + placed = true; |
| 57 | + break; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if (!placed) { |
| 63 | + result++; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return result; |
| 68 | +}; |
0 commit comments