[Egreedy] lc1710. The maximum number of units on the truck (greedy + weekly contest 222_1)

1. Source of the subject

Link: 5641. Maximum number of units on the truck

2. Topic analysis

It's been a long time since I played the weekly tournament, and I will try my best to follow along.

According to the number of cells in descending vectorsort can. That is vector[1]sort can be.

  • Time complexity : O (nlogn) O(nlogn)O ( n l o g n )
  • Space complexity : O (1) O (1)O ( 1 )

Code:

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;
    }
};

Guess you like

Origin blog.csdn.net/yl_puyu/article/details/112141604