You are given a set of N jobs where each job comes with a deadline and profit. The profit can only be earned upon completing the job within its deadline. Find the number of jobs done and the maximum profit that can be obtained. Each job takes a single unit of time and only one job can be performed at a time.
Sort jobs by deadline and greedily keep the most profitable set that fits deadlines. Use a min-heap of selected job profits: push a profit when the number of selected jobs is less than the current job's deadline; otherwise, if the current profit is larger than the smallest selected profit, replace it. The heap always contains the best profits for available slots.
class Solution {
public:
vector<int> jobSequencing(vector<int> &deadline, vector<int> &profit) {
int n = deadline.size();
vector<int> ans = {0, 0};
vector<pair<int, int>> jobs;
for (int i = 0; i < n; i++) {
jobs.push_back({deadline[i], profit[i]});
}
// sort the jobs based on deadline
// in ascending order
sort(jobs.begin(), jobs.end());
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 0; i < jobs.size(); i++) {
// if job can be scheduled within its deadline
if (jobs[i].first > pq.size())
pq.push(jobs[i].second);
// replace the job with the lowest profit
else if (!pq.empty() && pq.top() < jobs[i].second) {
pq.pop();
pq.push(jobs[i].second);
}
}
while (!pq.empty()) {
ans[1] += pq.top();
pq.pop();
ans[0]++;
}
return ans;
}
};