1710.卡车上的最大单元数
链接:1710.卡车上的最大单元数
难度:Easy
标签:贪心、数组、排序
简介:返回卡车可以装载 单元 的 最大 总数。
题解 1 - cpp
- 编辑时间:2022-11-15
- 执行用时:44ms
- 内存消耗:15.6MB
- 编程语言:cpp
- 解法介绍:排序后遍历。
class Solution {
public:
    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
        sort(boxTypes.begin(), boxTypes.end(), [](auto &a, auto &b){ return a[1] > b[1]; });
        int ans = 0, cur = 0;
        while (truckSize && cur < boxTypes.size()) {
            if (boxTypes[cur][0] >= truckSize) {
                ans += truckSize * boxTypes[cur][1];
                truckSize = 0;
            } else {
                truckSize -= boxTypes[cur][0];
                ans += boxTypes[cur][0] * boxTypes[cur][1];
            }
            cur++;
        }
        return ans;
    }
};