leetcode 826. 安排工作以达到最大收益

首先是自己写的构思代码
class Solution {
public:
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker){
sort(worker.begin(),worker.end());
int n = difficulty.size(),m = worker.size(),res = 0;
vector<pair<int,int>> diffProf;
for(int i = 0;i < n;++i) diffProf.emplace_back(make_pair(difficulty[i],profit[i]));
sort(diffProf.begin(),diffProf.end());
int maxProf = 0;
for(int i = 0,j = 0;i < n && j < m;){
while(i < n && diffProf[i].first <= worker[j]){
maxProf = max(maxProf,diffProf[i].second);
++i;
}
i = max(0,i-1);
if(diffProf[i].first > worker[j]){//这样的判断其实根本没有必要
++j;continue;
}
res += maxProf;
++j;
}
return res;
}
};
题解更优化的代码
class Solution {
public:
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker){
sort(worker.begin(),worker.end());
int n = difficulty.size(),m = worker.size(),res = 0;
vector<pair<int,int>> diffProf;
for(int i = 0;i < n;++i) diffProf.emplace_back(make_pair(difficulty[i],profit[i]));
sort(diffProf.begin(),diffProf.end());
int maxProf = 0,j = 0;
for(int &w : worker){
while(j < n && diffProf[j].first <= w){
maxProf = max(maxProf,diffProf[j].second);
++j;
}
res += maxProf;
}
return res;
}
};
浙公网安备 33010602011771号