Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

1710. Maximum Units on a Truck 🌟

You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:

You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Return the maximum total number of units that can be put on the truck.

Greedy

Code

class Solution {
    static bool comp(vector<int>& a, vector<int>& b)
    {
        return a[1] > b[1];
    }
public:
    int maximumUnits(vector<vector<int>>& boxTypes, int ts)
    {
        int n = boxTypes.size();
        sort(boxTypes.begin(), boxTypes.end(), comp);
        int cnt = 0;
        for (auto x : boxTypes) {
            if (x[0] <= ts) {
                cnt += x[0] * x[1];
                ts -= x[0];
            } else {
                cnt += ts * x[1];
                break;
            }
        }
        return cnt;
    }
};