Microsoft | Phone Screen | Job Sequencing Problem
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2022-04-08Added By Anonymous
Source: Link
Question:
Given a set of N jobs where each jobi has a deadline and profit associated with it.
Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit associated with job if and only if the job is completed by its deadline.
Find the number of jobs done and the maximum profit.
Note: Jobs will be given in the form (Jobid, Deadline, Profit) associated with that Job.
Example1:
1Input:
2N = 4
3Jobs = {(1,4,20),(2,1,10),(3,1,40),(4,1,30)}
4Output:
52 60
6Explanation:
7Job1 and Job3 can be done with
8maximum profit of 60 (20+40).Example2:
1Input:
2N = 5
3Jobs = {(1,2,100),(2,1,19),(3,2,27),
4 (4,1,25),(5,1,15)}
5Output:
62 127
7Explanation:
82 jobs can be done with
9maximum profit of 127 (100+27).Solution:
1/*
2struct Job
3{
4 int id; // Job Id
5 int dead; // Deadline of job
6 int profit; // Profit if job is over before or on deadline
7};
8*/
9class Solution
10{
11 public:
12 //Function to find the maximum profit and the number of jobs done.
13 static bool comp(const Job& job1, const Job& job2){
14 return job1.profit > job2.profit;
15 }
16
17 vector<int> JobScheduling(Job arr[], int n) {
18 // your code here
19 int max_deadline = arr[0].dead;
20 for(int i=1; i<n; i++)
21 max_deadline = max(max_deadline, arr[i].dead);
22
23 vector<int> sequence(max_deadline+1, -1);
24 sort(arr, arr+n, comp);
25
26 int countJobs=0;
27 int maxProfit=0;
28
29 for(int i=0; i<n; i++) {
30 for(int j=arr[i].dead; j>0; j--) {
31 if(sequence[j]==-1) {
32 sequence[j]=i;
33 countJobs++;
34 maxProfit+=arr[i].profit;
35 break;
36 }
37 }
38 }
39 return {countJobs, maxProfit};
40 }
41};