Approach
Sorting and greedy selection
For Maximize Profit from Task Assignment, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 32 lines of C++ from the credited upstream file 3476.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long maxProfit(vector<int>& workers, vector<vector<int>>& tasks) {4 long totalProfit = 0;5 int maxRemainingProfit = 0;6 unordered_map<int, vector<int>> skillToProfits;7 8 for (const vector<int>& task : tasks) {9 const int skill = task[0];10 const int profit = task[1];11 skillToProfits[skill].push_back(profit);12 }13 14 for (auto& [_, profits] : skillToProfits)15 ranges::sort(profits, greater<int>());16 17 for (const int workerSkill : workers)18 if (skillToProfits.contains(workerSkill) &&19 !skillToProfits[workerSkill].empty()) {20 const int profit = skillToProfits[workerSkill][0];21 skillToProfits[workerSkill].erase(skillToProfits[workerSkill].begin());22 totalProfit += profit;23 }24 25 for (const auto& [_, profits] : skillToProfits)26 if (!profits.empty())27 maxRemainingProfit = max(maxRemainingProfit, profits[0]);28 29 return totalProfit + maxRemainingProfit;30 }31};32