class Job {
id: number;
profit: number;
deadline: number;
constructor(id: number, profit: number, deadline: number) {
this.id = id;
this.profit = profit;
this.deadline = deadline;
}
}
function jobScheduling(jobs: Job[]): {schedule: (number | null)[], totalProfit: number} {
// Sort jobs by profit descending
jobs.sort((a, b) => b.profit - a.profit);
// Find max deadline to size schedule
const maxDeadline = jobs.length === 0 ? 0 : Math.max(...jobs.map(job => job.deadline));
// Initialize schedule slots with null (empty)
const schedule: (number | null)[] = new Array(maxDeadline).fill(null);
let totalProfit = 0;
for (const job of jobs) {
// Try to schedule job at latest free slot before deadline
for (let slot = Math.min(job.deadline, maxDeadline) - 1; slot >= 0; slot--) {
if (schedule[slot] === null) {
schedule[slot] = job.id; // assign job id to slot
totalProfit += job.profit;
break; // job scheduled, move to next job
}
}
}
return {schedule, totalProfit};
}
// Driver code
const jobs = [
new Job(1, 20, 2),
new Job(2, 15, 2),
new Job(3, 10, 1),
new Job(4, 5, 3),
new Job(5, 1, 3),
];
const result = jobScheduling(jobs);
console.log("Schedule slots (index+1):", result.schedule);
console.log("Total profit:", result.totalProfit);jobs.sort((a, b) => b.profit - a.profit);
Sort jobs by profit descending to prioritize high profit jobs
const maxDeadline = Math.max(...jobs.map(job => job.deadline));
Find maximum deadline to know schedule size
const schedule: (number | null)[] = new Array(maxDeadline).fill(null);
Initialize schedule slots as empty
for (const job of jobs) {
Iterate over jobs in profit order
for (let slot = Math.min(job.deadline, maxDeadline) - 1; slot >= 0; slot--) {
Try to assign job to latest free slot before deadline
if (schedule[slot] === null) {
Check if slot is free
schedule[slot] = job.id; totalProfit += job.profit; break;
Assign job to slot, add profit, stop searching slots
Schedule slots (index+1): [ 2, 1, 4 ]
Total profit: 40