본문 바로가기

Problem Solving/Leet Code

1710 Maximum Units on a Truck

Easy 난이도의 문제로 난이도대로 정말 쉽다

정렬만 해주면 바로 끝나는 문제이다.

 

C++

더보기
class Solution {
public:
    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
        auto f = [](vector<int> b1, vector<int> b2){return b1[1] > b2[1];};
        sort(boxTypes.begin(),boxTypes.end(),f);
        int cnt{};
        for(auto b : boxTypes){
            if (truckSize>= b[0]){
                truckSize -= b[0];
                cnt += b[0] * b[1];
            }
            else{
                cnt += b[1] * truckSize;
                return cnt;
            }
        }
        return cnt;
    }
};

Python

더보기
class Solution(object):
    def maximumUnits(self, boxTypes, truckSize):
        """
        :type boxTypes: List[List[int]]
        :type truckSize: int
        :rtype: int
        """
        boxTypes.sort(key = lambda x : -x[1])
        print(boxTypes)
        cnt = 0;
        for b in boxTypes:
            if truckSize >= b[0]:
                truckSize -= b[0]
                cnt += b[0] * b[1]
            else:
                cnt += b[1] * truckSize
                return cnt
        return cnt
        
728x90