[E贪心] lc1710. 卡车上的最大单元数(贪心+周赛222_1)

1. 题目来源

链接:5641. 卡车上的最大单元数

2. 题目解析

好久好久没打过周赛了,以后都会尽量跟着打了。

按单元数量从大到小对 vector 排序即可。即以 vector[1] 进行排序即可。

  • 时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn)
  • 空间复杂度 O ( 1 ) O(1) O(1)

代码:

class Solution {
    
    
public:
    int maximumUnits(vector<vector<int>>& a, int b) {
    
    
        sort(a.begin(), a.end(), [](vector<int> a, vector<int> b) {
    
    
            return a[1] > b[1];
        });
        int res = 0;
        for (int i = 0; i < a.size() && b > 0; i ++ ) {
    
    
            int cur = min(a[i][0], b);
            res += cur * a[i][1];
            b -= a[i][0];
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/yl_puyu/article/details/112141604
今日推荐