.Zzumbong

[leetCode/JS] 3074. Apple Redistribution into Boxes 본문

coding test/leetCode

[leetCode/JS] 3074. Apple Redistribution into Boxes

쭘봉 2025. 12. 29. 16:39

난이도 [ 😊 ] Easy

 

문제 설명 

You are given an array apple of size n and an array capacity of size m. There are n packs where the ith pack contains apple[i] apples. There are m boxes as well, and the ith box has a capacity of capacity[i] apples. Return the minimum number of boxes you need to select to redistribute these n packs of apples into boxes. Note that, apples from the same pack can be distributed into different boxes.

당신에게는 크기가 n인 apple 배열과 크기가 m인 capacity 배열이 주어집니다.
n개의 팩이 있으며, i번째 팩에는 apple[i]개의 사과가 들어있습니다. 또한 m개의 상자가 있으며, i번째 상자는 capacity[i]개의 사과를 담을 수 있는 용량을 가지고 있습니다.
이 n팩의 사과들을 상자들에 다시 나누어 담기 위해 선택해야 하는 상자의 최소 개수를 반환하세요.
단, 같은 팩에 들어있던 사과들이라도 서로 다른 상자에 나누어서 담을 수 있다는 점에 유의하세요.

어렵게 설명 되어있는데, 사과의 Array는 의미가 없음. 총 사과가 몇개고, 몇개의 상자(capacity)로 담을 수 있느냐가 문제.

 

입출력 예

Example 1:

Input: apple = [1,3,2], capacity = [4,3,1,5,2]
Output: 2 Explanation: We will use boxes with capacities 4 and 5. 
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. 

입출력 예

Example 2:

Input: apple = [5,5,5], capacity = [2,4,2,7]
Output: 4 Explanation: We will need to use all the boxes.

 

Constraints

  • 1 <= n == apple.length <= 50 
  • 1 <= m == capacity.length <= 50 
  • 1 <= apple[i], capacity[i] <= 50 
  • The input is generated such that it's possible to redistribute packs of apples into boxes.

여기서 사과나 용량 배열은 숫자가 작구나를 파악하면 굿

 

 


내 솔루션

/**
 * https://leetcode.com/problems/apple-redistribution-into-boxes
 * @param {number[]} apple
 * @param {number[]} capacity
 * @return {number}
 */
 
// 처음 푼 문제
var minimumBoxes = function(apple, capacity) {
    const apples = apple.reduce((cur, acc) => acc += cur, 0)
    let sum = 0;
    let answer = 0;
    const sorted = capacity.sort((a, b) => b - a);
    
    for(let i = 0; i < sorted.length; i++){
        sum += sorted[i];
        if(sum >= apples) {
            answer = (i+1);
            break;
        }
    }
    return answer;
};


// While과 sum으로 더하는 방식이 빼는 방식으로 최적화
var minimumBoxes = function(apple, capacity) {
    let apples = apple.reduce((cur, acc) => acc + cur, 0)
    capacity.sort((a, b) => b - a);
    
    let idx = 0;
    while(apples > 0) {
        apples -= capacity[idx++]
    }
    return idx;
};

 

감상평

  • 코테에서 나오면 5분컷 내야하는 문제긴한데, 좀 더 걸림

Comments