작심삼일

[LeetCode] 1710 | Maximum Units on an Truck | Python 본문

스터디/코테

[LeetCode] 1710 | Maximum Units on an Truck | Python

yun_s 2022. 7. 1. 10:14
728x90
반응형

문제 링크: https://leetcode.com/problems/maximum-units-on-a-truck/


문제

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

  • $numberOfBoxes_i$ is the number of boxes of type i.
  • $numberOfUnitsPerBox_i$ 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.


조건

  • 1 <= boxTypes.length <= 1000
  • 1 <= $numberOfBoxes_i$, $numberOfUnitsPerBox_i$ <= 1000
  • 1 <= truckSize <= $10^6$

내 풀이

boxTypes의 원소가 [박스 수, 박스에 들어있는 것의 갯수]임을 기억하자.

'박스에 들어있는 것의 갯수'가 큰 박스가 많을수록 좋기 때문에, 이것이 큰 순서대로 boxTypes를 정렬한다.

앞에서부터 차례로 박스를 넣으면 된다.


코드

class Solution:
    def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
        boxTypes.sort(key=lambda x: x[1], reverse=True)
        ans = 0
        
        for box, unit in boxTypes:
            if box <= truckSize:
                ans += box*unit
                truckSize -= box
            else:
                ans += truckSize*unit
                break
            
        return ans
728x90
반응형
Comments