[1710] Maximum Units on a Truck | Leetcode Easy

yoongyum·2022년 7월 1일
0

코딩테스트 🧩

목록 보기
41/47
post-thumbnail

🔎문제설명

You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:

numberOfBoxesi is the number of boxes of type i.
numberOfUnitsPerBoxi is the number of units in each box of the type i.
You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Return the maximum total number of units that can be put on the truck.

### 한글요약
2차원 배열이 주어집니다. 하나는 박스별 상자수, 두번째는 각 상자의 단위입니다.
그리고 트럭의 최대사이즈가 주어집니다.

트럭에 실을 수 있는 최대 수를 반환합니다.

Example 1

Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.

Example 2

Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91

제한사항
1 <= boxTypes.length <= 1000
1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
1 <= truckSize <= 10610^6




🧊파이썬 코드

먼저 상자 유닛수를 기준으로 정렬을 했습니다.
트럭에 박스의 수가 넘는 경우에는 다 더하지 않고 남은 공간만큼만 더합니다.

class Solution:
    def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
        
        
        boxTypes.sort(key=lambda x : -x[1]) #유닛크기로 정렬
        
        maxi = 0
        
        for box in boxTypes:
            num_boxes, num_units = box[0], box[1]
            if truckSize < num_boxes:
                maxi += truckSize * num_units
                break;
            maxi += num_boxes * num_units
            truckSize -= num_boxes
                
        return maxi

0개의 댓글