[JAVA 문제 풀이] 413. Fruits Into Baskets II

[바구니에 과일 담기 II]
Stupefyee's avatar
Aug 05, 2025
[JAVA 문제 풀이] 413. Fruits Into Baskets II
Fruits Into Baskets II - LeetCode
Can you solve this real interview question? Fruits Into Baskets II - You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i] represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of the jth basket. From left to right, place the fruits according to these rules: * Each fruit type must be placed in the leftmost available basket with a capacity greater than or equal to the quantity of that fruit type. * Each basket can hold only one type of fruit. * If a fruit type cannot be placed in any basket, it remains unplaced. Return the number of fruit types that remain unplaced after all possible allocations are made.   Example 1: Input: fruits = [4,2,5], baskets = [3,5,4] Output: 1 Explanation: * fruits[0] = 4 is placed in baskets[1] = 5. * fruits[1] = 2 is placed in baskets[0] = 3. * fruits[2] = 5 cannot be placed in baskets[2] = 4. Since one fruit type remains unplaced, we return 1. Example 2: Input: fruits = [3,6,1], baskets = [6,4,7] Output: 0 Explanation: * fruits[0] = 3 is placed in baskets[0] = 6. * fruits[1] = 6 cannot be placed in baskets[1] = 4 (insufficient capacity) but can be placed in the next available basket, baskets[2] = 7. * fruits[2] = 1 is placed in baskets[1] = 4. Since all fruits are successfully placed, we return 0.   Constraints: * n == fruits.length == baskets.length * 1 <= n <= 100 * 1 <= fruits[i], baskets[i] <= 1000
Fruits Into Baskets II - LeetCode
notion image
notion image
과일과 바구니라는 두 개의 정수 배열이 주어지는데, 각각의 길이 n은 과일의 i번째 유형의 양을 나타내고, 바구니[j]는 j번째 바구니의 용량을 나타냅니다. 왼쪽에서 오른쪽으로 과일을 다음 규칙에 따라 배치하세요: * 각 과일 종류는 해당 과일 종류의 양보다 크거나 같은 용량으로 가장 왼쪽에 있는 바구니에 넣어야 합니다. * 각 바구니에는 한 가지 종류의 과일만 담을 수 있습니다. * 과일 종류를 바구니에 넣을 수 없는 경우, 그대로 둡니다. 가능한 모든 할당이 완료된 후에도 배치되지 않은 과일 종류의 수를 반환합니다. 제약 사항: * n == fruits.length == baskets.length * 1 <= n <= 100 * 1 <= fruits[i], baskets[i] <= 1000
 

내가 작성한 코드

class Solution { public int numOfUnplacedFruits(int[] fruits, int[] baskets) { int n = fruits.length; boolean[] used = new boolean[n]; // 바구니 사용 여부 int unplaced = 0; // 못 넣은 과일 개수 for (int i = 0; i < n; i++) { boolean placed = false; for (int j = 0; j < n; j++) { // 바구니가 사용 안 되었고, 용량이 과일 수보다 크거나 같으면 사용 if (!used[j] && baskets[j] >= fruits[i]) { used[j] = true; // 바구니 사용 placed = true; // 배치 성공 break; } } // 과일을 배치하지 못한 경우 if (!placed) { unplaced++; // 못 넣은 과일 개수 증가 } } return unplaced; } }
Share article

stupefyee