Given an array of jobs where every job has a deadline and associated profit if the job is finished before the deadline. It is also given that every job takes a single unit of time, so the minimum possible deadline for any job is 1. Maximize the total profit if only one job can be scheduled at a time.
Examples:
Input: Four Jobs with following deadlines and profits
JobID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output: Following is maximum profit sequence of jobs: c, a
Input: Five Jobs with following deadlines and profits
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output: Following is maximum profit sequence of jobs: d, a, e
Using Greedy Approach with Extra Space
Follow the given steps to solve the problem:
- Sort the jobs by profit: The first step is to sort the jobs in descending order of their profit because we want to maximize the profit by performing the highest-paying jobs first.
- Create time slots: We create an array slot[] to keep track of which time slots are available (free) and an array result[] to store the job sequence.
- Job scheduling: For each job, try to find a free time slot before or on its deadline (starting from the last possible time slot). If such a time slot is available, assign the job to it.
- Output the job sequence: Finally, print the job sequence that yields the maximum profit. Only jobs that are scheduled in valid time slots are printed.
Below is the implementation of the above approach:
C++
#include <algorithm> // For sort function
#include <iostream> // For input-output operations
using namespace std;
// Structure to represent a job with its id, deadline, and profit
struct Job {
char id; // Job Id
int dead; // Deadline of the job
int profit; // Profit if the job is done before or on the deadline
};
// Comparison function to sort jobs based on descending order of profit
bool comparison(Job a, Job b) {
return (a.profit > b.profit); // Return true if profit of job 'a' is greater than that of 'b'
}
// Function to schedule jobs for maximum profit
void printJobScheduling(Job arr[], int n) {
// Step 1: Sort all jobs in descending order of profit
sort(arr, arr + n, comparison); // Sort jobs using the comparison function
// Step 2: Create an array to keep track of free time slots
bool slot[n] = {false}; // Initially, all time slots are free (false)
// Step 3: Create an array to store result of the job sequence
char result[n] = {0}; // Result array will store the job ids scheduled
// Step 4: Iterate through all given jobs
for (int i = 0; i < n; i++) {
// Check if the job can be scheduled before or on its deadline
// We start checking from the last possible free slot before the deadline
if(slot[arr[i].dead] == false) { // If the slot for this job's deadline is free
result[i] = arr[i].id; // Assign the job id to the result
slot[arr[i].dead] = true; // Mark this slot as filled
}
}
// Step 5: Output the scheduled jobs (only those in valid slots)
for (int i = 0; i < n; i++) {
if (slot[arr[i].dead]) { // If the slot was filled
if(result[i] != 0) // Check if the result has a valid job id
cout << result[i] << " "; // Print the job id
}
}
cout << endl;
}
int main() {
// Array of jobs with id, deadline, and profit
Job arr[] = { {'a', 2, 100},
{'b', 1, 19},
{'c', 2, 27},
{'d', 1, 25},
{'e', 3, 15} };
// Number of jobs
int n = sizeof(arr) / sizeof(arr[0]);
// Print the result of the job scheduling
cout << "Following is the maximum profit sequence of jobs:\n";
printJobScheduling(arr, n);
return 0;
}
// Code is contributed by Pratham Lashkari
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Structure to represent a job with its id, deadline, and profit
struct Job {
char id;
int dead;
int profit;
};
// Comparison function to sort jobs based on descending order of profit
int comparison(const void *a, const void *b) {
return ((struct Job*)b)->profit - ((struct Job*)a)->profit;
}
// Function to schedule jobs for maximum profit
void printJobScheduling(struct Job arr[], int n) {
// Step 1: Sort jobs in descending order of profit
qsort(arr, n, sizeof(struct Job), comparison);
// Step 2: Create arrays for result and time slots
bool slot[n];
char result[n];
for (int i = 0; i < n; i++) {
slot[i] = false;
result[i] = 0;
}
// Step 3: Iterate through all jobs
for (int i = 0; i < n; i++) {
if (!slot[arr[i].dead - 1]) { // Check if the slot is free
result[i] = arr[i].id;
slot[arr[i].dead - 1] = true; // Mark this slot as filled
}
}
// Step 4: Output the scheduled jobs
for (int i = 0; i < n; i++) {
if (result[i] != 0) {
printf("%c ", result[i]);
}
}
printf("\n");
}
int main() {
struct Job arr[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27},
{'d', 1, 25}, {'e', 3, 15} };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Following is the maximum profit sequence of jobs:\n");
printJobScheduling(arr, n);
return 0;
}
// Code is contributed by Pratham Lashkari
Java
import java.util.Arrays;
class Job {
char id;
int dead;
int profit;
// Constructor
Job(char id, int dead, int profit) {
this.id = id;
this.dead = dead;
this.profit = profit;
}
}
public class JobScheduling {
public static void printJobScheduling(Job[] arr, int n) {
// Step 1: Sort jobs in descending order of profit
Arrays.sort(arr, (a, b) -> b.profit - a.profit);
// Step 2: Create arrays for result and time slots
boolean[] slot = new boolean[n];
char[] result = new char[n];
// Step 3: Iterate through all jobs
for (int i = 0; i < n; i++) {
if (slot[arr[i].dead - 1] == false) { // Check if the slot is free
result[i] = arr[i].id;
slot[arr[i].dead - 1] = true; // Mark this slot as filled
}
}
// Step 4: Output the scheduled jobs
for (char job : result) {
if (job != 0) {
System.out.print(job + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
Job[] arr = { new Job('a', 2, 100), new Job('b', 1, 19), new Job('c', 2, 27),
new Job('d', 1, 25), new Job('e', 3, 15) };
int n = arr.length;
System.out.println("Following is the maximum profit sequence of jobs:");
printJobScheduling(arr, n);
}
}
// Code is contributed by Pratham Lashkari
Python
class Job:
def __init__(self, id, deadline, profit):
self.id = id
self.deadline = deadline
self.profit = profit
def job_scheduling(arr, n):
# Step 1: Sort jobs in descending order of profit
arr.sort(key=lambda x: x.profit, reverse=True)
# Step 2: Initialize result and slot arrays
result = [''] * n
slot = [False] * n
# Step 3: Iterate through all jobs
for i in range(n):
if not slot[arr[i].deadline - 1]: # Check if slot is free
result[i] = arr[i].id
slot[arr[i].deadline - 1] = True # Mark this slot as filled
# Step 4: Output the scheduled jobs
for job in result:
if job:
print(job, end=" ")
print()
if __name__ == '__main__':
arr = [Job('a', 2, 100), Job('b', 1, 19), Job('c', 2, 27),
Job('d', 1, 25), Job('e', 3, 15)]
n = len(arr)
print("Following is the maximum profit sequence of jobs:")
job_scheduling(arr, n)
# Code is contributed by Pratham Lashkari
C#
using System;
class Job {
public char id;
public int dead;
public int profit;
// Constructor
public Job(char id, int dead, int profit) {
this.id = id;
this.dead = dead;
this.profit = profit;
}
}
class JobScheduling {
public static void PrintJobScheduling(Job[] arr, int n) {
// Step 1: Sort jobs in descending order of profit
Array.Sort(arr, (a, b) => b.profit.CompareTo(a.profit));
// Step 2: Create arrays for result and time slots
bool[] slot = new bool[n];
char[] result = new char[n];
// Step 3: Iterate through all jobs
for (int i = 0; i < n; i++) {
if (!slot[arr[i].dead - 1]) { // Check if the slot is free
result[i] = arr[i].id;
slot[arr[i].dead - 1] = true; // Mark this slot as filled
}
}
// Step 4: Output the scheduled jobs
foreach (var job in result) {
if (job != '\0') {
Console.Write(job + " ");
}
}
Console.WriteLine();
}
public static void Main(string[] args) {
Job[] arr = {
new Job('a', 2, 100),
new Job('b', 1, 19),
new Job('c', 2, 27),
new Job('d', 1, 25),
new Job('e', 3, 15)
};
int n = arr.Length;
Console.WriteLine("Following is the maximum profit sequence of jobs:");
PrintJobScheduling(arr, n);
}
}
// Code is contributed by Pratham Lashkari
JavaScript
class Job {
constructor(id, deadline, profit) {
this.id = id;
this.deadline = deadline;
this.profit = profit;
}
}
function jobScheduling(arr, n) {
// Step 1: Sort jobs in descending order of profit
arr.sort((a, b) => b.profit - a.profit);
// Step 2: Initialize result and slot arrays
let result = Array(n).fill('');
let slot = Array(n).fill(false);
// Step 3: Iterate through all jobs
for (let i = 0; i < n; i++) {
if (!slot[arr[i].deadline - 1]) { // Check if slot is free
result[i] = arr[i].id;
slot[arr[i].deadline - 1] = true; // Mark this slot as filled
}
}
// Step 4: Output the scheduled jobs
result.forEach(job => {
if (job) {
process.stdout.write(job + " ");
}
});
console.log();
}
let arr = [
new Job('a', 2, 100),
new Job('b', 1, 19),
new Job('c', 2, 27),
new Job('d', 1, 25),
new Job('e', 3, 15)
];
let n = arr.length;
console.log("Following is the maximum profit sequence of jobs:");
jobScheduling(arr, n);
// Code is contributed by Pratham Lashkari
OutputFollowing is the maximum profit sequence of jobs:
a d e
Time Complexity:
- Sorting the jobs by profit: Sorting takes 𝑂(𝑛log𝑛),where 𝑛 is the number of jobs.
- Finding a free slot for each job: For each job, in the worst case, we might need to check up n slots. This O(n) for each job, so n jobs, it O(n^2).
Auxiliary Space: O(N) of result and slot array
Using Priority-Queue (Max-Heap):
Sort the jobs in the increasing order of their deadlines and then calculate the available slots between every two consecutive deadlines while iterating from the end. Include the profit of the job at the root of the Max-Heap while the empty slots are available and Heap is not empty, as this would help to choose the jobs with maximum profit for every set of available slots.
Follow the given steps to solve the problem:
- Sort the jobs based on their deadlines.
- Iterate from the end and calculate the available slots between every two consecutive deadlines. Insert the profit, deadline, and job ID of ith job in the max heap.
- While the slots are available and there are jobs left in the max heap, include the job ID with maximum profit and deadline in the result.
- Sort the result array based on their deadlines.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// A structure to represent a job
struct Job
{
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit earned if job is completed before
// deadline
};
// Custom sorting helper struct which is used for sorting
// all jobs according to profit
struct jobProfit
{
bool operator()(Job const &a, Job const &b)
{
return (a.profit < b.profit);
}
};
// Returns maximum profit from jobs
void printJobScheduling(Job arr[], int n)
{
vector<Job> result;
sort(arr, arr + n, [](Job a, Job b) { return a.dead < b.dead; });
// set a custom priority queue
priority_queue<Job, vector<Job>, jobProfit> pq;
for (int i = n - 1; i >= 0; i--)
{
int slot_available;
// we count the slots available between two jobs
if (i == 0)
{
slot_available = arr[i].dead;
}
else
{
slot_available = arr[i].dead - arr[i - 1].dead;
}
// if we found same slot than check its profit if it is small than ignore it
if (arr[i].dead == arr[i - 1].dead)
{
if (arr[i].profit > arr[i - 1].profit)
pq.push(arr[i]);
}
else
{
pq.push(arr[i]);
}
while (slot_available > 0 && pq.size() > 0)
{
// get the job with the most profit
Job job = pq.top();
pq.pop();
// reduce the slots
slot_available--;
// add it to the answer
result.push_back(job);
}
}
// sort the result based on the deadline
sort(result.begin(), result.end(), [&](Job a, Job b) { return a.dead < b.dead; });
// print the result
for (int i = 0; i < result.size(); i++)
cout << result[i].id << ' ';
cout << endl;
}
// Driver's code
int main()
{
Job arr[] = {{'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1, 25}, {'e', 3, 15}};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Following is maximum profit sequence of jobs "
"\n";
// Function call
printJobScheduling(arr, n);
return 0;
}
// Code is contributed by Pratham Lashkari
C
#include <stdio.h>
#include <stdlib.h>
typedef struct Job
{
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit of job
} Job;
// Comparison function to sort jobs by deadline
int compareJobs(const void *a, const void *b)
{
return ((Job *)a)->dead - ((Job *)b)->dead;
}
// Returns the max profit job sequence
void jobScheduling(Job arr[], int n)
{
// Sort jobs by deadline
qsort(arr, n, sizeof(Job), compareJobs);
Job result[100]; // Result array to store selected jobs
int resultSize = 0;
// Iterate over jobs from last to first
for (int i = n - 1; i >= 0; i--)
{
int slot_available = (i == 0) ? arr[i].dead : arr[i].dead - arr[i - 1].dead;
if (i > 0 && arr[i].dead == arr[i - 1].dead)
{
if (arr[i].profit > arr[i - 1].profit)
{
result[resultSize++] = arr[i];
}
}
else
{
result[resultSize++] = arr[i];
}
}
// Print the result
for (int i = 0; i < resultSize; i++)
{
printf("%c ", result[i].id);
}
printf("\n");
}
int main()
{
Job arr[] = {{'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1, 25}, {'e', 3, 15}};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Following is maximum profit sequence of jobs:\n");
jobScheduling(arr, n);
return 0;
}
// Code is contributed by Pratham Lashkari
Java
import java.util.*;
// A class to represent a job
class Job {
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit earned if job is completed before
// deadline
public Job(char id, int dead, int profit)
{
this.id = id;
this.dead = dead;
this.profit = profit;
}
}
class JobProfit implements Comparator<Job> {
// Custom comparator to sort jobs by profit in
// descending order
public int compare(Job a, Job b)
{
return b.profit - a.profit;
}
}
public class JobScheduling {
public static void printJobScheduling(Job[] arr, int n)
{
// Result array to store selected jobs
List<Job> result = new ArrayList<>();
// Sort jobs by deadline in ascending order
Arrays.sort(arr, (a, b) -> a.dead - b.dead);
// Priority queue to select jobs with maximum profit
PriorityQueue<Job> pq
= new PriorityQueue<>(new JobProfit());
for (int i = n - 1; i >= 0; i--) {
int slot_available;
// Count available slots between two jobs
if (i == 0) {
slot_available = arr[i].dead;
}
else {
slot_available
= arr[i].dead - arr[i - 1].dead;
}
// Push job with the higher profit if two jobs
// have the same deadline
if (i > 0 && arr[i].dead == arr[i - 1].dead) {
if (arr[i].profit > arr[i - 1].profit) {
pq.add(arr[i]);
}
}
else {
pq.add(arr[i]);
}
// Select jobs as long as there are available
// slots
while (slot_available > 0 && !pq.isEmpty()) {
Job job = pq.poll();
slot_available--;
result.add(job);
}
}
// Sort selected jobs by deadline for output
result.sort((a, b) -> a.dead - b.dead);
// Print selected job sequence
for (Job job : result) {
System.out.print(job.id + " ");
}
System.out.println();
}
public static void main(String[] args)
{
Job[] arr
= { new Job('a', 2, 100), new Job('b', 1, 19),
new Job('c', 2, 27), new Job('d', 1, 25),
new Job('e', 3, 15) };
System.out.println(
"Following is maximum profit sequence of jobs: ");
printJobScheduling(arr, arr.length);
}
}
// Code is contributed by Pratham Lashkari
Python
import heapq
class Job:
def __init__(self, id, dead, profit):
self.id = id # Job Id
self.dead = dead # Deadline of job
self.profit = profit # Profit of job
def job_scheduling(arr, n):
result = [] # Result list to store selected jobs
# Sort jobs by deadline
arr.sort(key=lambda x: x.dead)
pq = [] # Priority queue to store jobs with max profit
for i in range(n - 1, -1, -1):
slot_available = arr[i].dead if i == 0 else arr[i].dead - \
arr[i - 1].dead
if i > 0 and arr[i].dead == arr[i - 1].dead:
if arr[i].profit > arr[i - 1].profit:
heapq.heappush(pq, (-arr[i].profit, arr[i]))
else:
heapq.heappush(pq, (-arr[i].profit, arr[i]))
while slot_available > 0 and pq:
profit, job = heapq.heappop(pq)
result.append(job)
slot_available -= 1
result.sort(key=lambda x: x.dead)
# Print the result
for job in result:
print(job.id, end=" ")
print()
# Driver code
arr = [Job('a', 2, 100),
Job('b', 1, 19),
Job('c', 2, 27),
Job('d', 1, 25),
Job('e', 3, 15)]
print("Following is maximum profit sequence of jobs: ")
job_scheduling(arr, len(arr))
# Code is contributed by Pratham Lashkari
C#
using System;
using System.Collections.Generic;
namespace GFG
{
// A class to represent a job
public class Job
{
public char JobId { get; set; }
public int Deadline { get; set; }
public int Profit { get; set; }
public Job(char jobId, int deadline, int profit)
{
this.Deadline = deadline;
this.JobId = jobId;
this.Profit = profit;
}
}
class Scheduling
{
static void PrintJobScheduling(List<Job> jobs)
{
// Step 1: Sort jobs in descending order of profit
jobs.Sort((a, b) => b.Profit.CompareTo(a.Profit));
int n = jobs.Count;
// Step 2: Find the maximum deadline
int maxDeadline = 0;
foreach (var job in jobs)
{
if (job.Deadline > maxDeadline)
{
maxDeadline = job.Deadline;
}
}
// Step 3: Initialize result array and slot tracker
char[] result = new char[maxDeadline];
bool[] slot = new bool[maxDeadline];
for (int i = 0; i < maxDeadline; i++)
{
slot[i] = false;
}
// Step 4: Iterate through all jobs
foreach (var job in jobs)
{
// Find a free slot for this job (starting from its deadline)
for (int j = Math.Min(maxDeadline - 1, job.Deadline - 1); j >= 0; j--)
{
if (!slot[j])
{
// Assign this job to the slot
result[j] = job.JobId;
slot[j] = true;
break;
}
}
}
// Step 5: Print the job sequence for maximum profit
Console.WriteLine("Following is the maximum profit sequence of jobs:");
foreach (var job in result)
{
if (job != '\0') // Ignore empty slots
{
Console.Write(job + " ");
}
}
Console.WriteLine();
}
// Driver Code
static void Main(string[] args)
{
List<Job> jobs = new List<Job>
{
new Job('a', 2, 100),
new Job('b', 1, 19),
new Job('c', 2, 27),
new Job('d', 1, 25),
new Job('e', 3, 15)
};
// Function call
PrintJobScheduling(jobs);
}
}
}
JavaScript
class Job {
constructor(id, dead, profit)
{
this.id = id; // Job Id
this.dead = dead; // Deadline of job
this.profit = profit; // Profit of job
}
}
function jobScheduling(arr, n)
{
// Sort jobs by deadline in ascending order
arr.sort((a, b) => a.dead - b.dead);
let result =
[]; // Result array to store the selected jobs
let pq =
[]; // Priority queue to store jobs based on profit
for (let i = n - 1; i >= 0; i--) {
let slot_available
= (i === 0) ? arr[i].dead
: arr[i].dead - arr[i - 1].dead;
if (i > 0 && arr[i].dead === arr[i - 1].dead) {
if (arr[i].profit > arr[i - 1].profit) {
pq.push(arr[i]);
}
}
else {
pq.push(arr[i]);
}
pq.sort(
(a,
b) => b.profit
- a.profit); // Sort by profit (max heap)
while (slot_available > 0 && pq.length > 0) {
let job = pq.shift(); // Get job with max profit
slot_available--;
result.push(job);
}
}
// Sort selected jobs by deadline
result.sort((a, b) => a.dead - b.dead);
// Print the result
result.forEach(
job => { process.stdout.write(job.id + " "); });
console.log();
}
let arr = [
new Job("a", 2, 100), new Job("b", 1, 19),
new Job("c", 2, 27), new Job("d", 1, 25),
new Job("e", 3, 15)
];
console.log(
"Following is maximum profit sequence of jobs: ");
jobScheduling(arr, arr.length);
// Code is contributed by Pratham Lashkari
OutputFollowing is maximum profit sequence of jobs
d a e
Time Complexity: O(N log N)
Auxiliary Space: O(N)
It can also be optimized using Disjoint Set Data Structure. Please refer to the below post for details.
Job Sequencing Problem | Set 2 (Using Disjoint Set)