-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathJob_Sequencing_Problem.cpp
More file actions
75 lines (57 loc) · 2.11 KB
/
Job_Sequencing_Problem.cpp
File metadata and controls
75 lines (57 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Problem Statement: 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.
// Example 1:
// Input: N = 4, Jobs = {(1,4,20),(2,1,10),(3,1,40),(4,1,30)}
// Output: 2 60
// Explanation: The 3rd job with a deadline 1 is performed during the first unit of time .The 1st job is performed during the second unit of time as its deadline is 4.
// Profit = 40 + 20 = 60
// Example 2:
// Input: N = 5, Jobs = {(1,2,100),(2,1,19),(3,2,27),(4,1,25),(5,1,15)}
// Output: 2 127
// Explanation: The first and third job both having a deadline 2 give the highest profit.
// Profit = 100 + 27 = 127
#include<bits/stdc++.h>
using namespace std;
// A structure to represent a job
struct Job {
int id; // Job Id
int dead; // Deadline of job
int profit; // Profit if job is over before or on deadline
};
class Solution {
public:
bool static comparison(Job a, Job b) {
return (a.profit > b.profit);
}
//Function to find the maximum profit and the number of jobs done
pair < int, int > JobScheduling(Job arr[], int n) {
sort(arr, arr + n, comparison);
int maxi = arr[0].dead;
for (int i = 1; i < n; i++) {
maxi = max(maxi, arr[i].dead);
}
int slot[maxi + 1];
for (int i = 0; i <= maxi; i++)
slot[i] = -1;
int countJobs = 0, jobProfit = 0;
for (int i = 0; i < n; i++) {
for (int j = arr[i].dead; j > 0; j--) {
if (slot[j] == -1) {
slot[j] = i;
countJobs++;
jobProfit += arr[i].profit;
break;
}
}
}
return make_pair(countJobs, jobProfit);
}
};
int main() {
int n = 4;
Job arr[n] = {{1,4,20},{2,1,10},{3,2,40},{4,2,30}};
Solution ob;
//function call
pair < int, int > ans = ob.JobScheduling(arr, n);
cout << ans.first << " " << ans.second << endl;
return 0;
}