Skip to content

Commit a763eba

Browse files
committed
🎉 Job Sequencing Problem
1 parent e5f4d5f commit a763eba

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Job implements Comparable<Job> {
2+
3+
Character id = 'a';
4+
Integer deadline = 0;
5+
Integer profit = 0;
6+
7+
Job(Character Jobid, Integer dl, Integer pr) {
8+
id = Jobid;
9+
deadline = dl;
10+
profit = pr;
11+
}
12+
13+
@Override
14+
public int compareTo(Job job) {
15+
return job.profit.compareTo(this.profit);
16+
}
17+
18+
@Override
19+
public String toString() {
20+
return "["+ id+ "], ";
21+
}
22+
23+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Given an array of jobs where every job has a deadline and
3+
* associated profit if the job is finished before the deadline.
4+
* It is also given that every job takes single unit of time,
5+
* so the minimum possible deadline for any job is 1.
6+
* How to maximize total profit if only one job can be scheduled at a time.
7+
*
8+
*
9+
* TIME COMPLEXITY : O(n^2)
10+
* It can be optimized using Disjoint Set Data Structure
11+
*/
12+
13+
14+
import java.util.ArrayList;
15+
import java.util.Collections;
16+
import java.util.Random;
17+
18+
public class JobSequencingProblem {
19+
20+
public static void selectJobs() {
21+
22+
ArrayList<Job> jobs = new ArrayList<Job>();
23+
24+
jobs.add(new Job('a',2,100));
25+
jobs.add(new Job('b',1,19));
26+
jobs.add(new Job('c',2,27));
27+
jobs.add(new Job('d',1,25));
28+
jobs.add(new Job('e',3,15));
29+
30+
Collections.sort(jobs);
31+
32+
int size = jobs.size();
33+
34+
int[] result = new int[size];
35+
boolean[] slot = new boolean[size];
36+
37+
for(int i=0; i<size; i++){
38+
int dl = jobs.get(i).deadline;
39+
for(int j= Math.min(size, dl)-1; j>=0; j--){
40+
if(slot[j] == false){
41+
result[j] = i;
42+
slot[j] = true;
43+
break;
44+
}
45+
}
46+
}
47+
48+
for(int i=0; i<size; i++){
49+
if(slot[i]){
50+
System.out.println(jobs.get(result[i]).id);
51+
}
52+
}
53+
}
54+
55+
public static void main(String[] args){
56+
selectJobs();
57+
}
58+
}

0 commit comments

Comments
 (0)