Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
관리 메뉴

hwooo

LeetCode (C/C++) 1710. Maximum Units on a Truck 본문

Study/Algorithm

LeetCode (C/C++) 1710. Maximum Units on a Truck

hwooo 2024. 6. 3. 17:23

https://leetcode.com/problems/maximum-units-on-a-truck/description/


풀이

numberOfUnitsPerBox 기준 내림차순 정렬 후 numberOfUnitsPerBox가 큰 것부터 차례로 넣어 maximumUnits 도출


코드

class Solution {
public:
    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {

        // numberOfUnitsPerBox 기준 내림차순 정렬
        sort(boxTypes.begin(), boxTypes.end(), [](vector<int> &a, vector<int> &b){
            return a[1] > b[1];
        });

        // numberOfUnitsPerBox가 큰 것부터 차례로 넣어 maximumUnits 도출
        int maxUnits = 0;
        for (int i = 0; i < boxTypes.size(); i++) {
            int cnt = min(boxTypes[i][0], truckSize);

            maxUnits += boxTypes[i][1] * cnt;
            truckSize -= cnt;
            if (!truckSize)
                return maxUnits;
        }
        return maxUnits;
    }
};