interface Job {
id: string;
deadline: number;
profit: number;
}
function jobScheduling(jobs: Job[]): string {
jobs.sort((a, b) => b.profit - a.profit);
const n = jobs.length;
const result: (string | null)[] = Array(n).fill(null);
const slot: boolean[] = Array(n).fill(false);
for (let i = 0; i < n; i++) {
for (let j = Math.min(n - 1, jobs[i].deadline - 1); j >= 0; j--) {
if (!slot[j]) {
slot[j] = true;
result[j] = jobs[i].id;
break;
}
}
}
return result.filter(x => x !== null).join(' -> ') + ' -> null';
}
const jobs: Job[] = [
{ id: 'a', deadline: 2, profit: 100 },
{ id: 'b', deadline: 1, profit: 19 },
{ id: 'c', deadline: 2, profit: 27 },
{ id: 'd', deadline: 1, profit: 25 },
{ id: 'e', deadline: 3, profit: 15 }
];
console.log(jobScheduling(jobs));The jobs are sorted by profit: a(100), c(27), d(25), b(19), e(15).
Assign 'a' to slot 1 (deadline 2), 'c' to slot 0 (deadline 2), and 'e' to slot 2 (deadline 3). Slots 0,1,2 correspond to time slots 1,2,3 respectively.
Resulting schedule is "a -> c -> e -> null".
Maximum slots available are 3 (max deadline).
By scheduling jobs with highest profit first, we can schedule 3 jobs without conflicts.
The code sorts jobs by ascending profit, which schedules low profit jobs first.
This leads to suboptimal total profit and incorrect scheduling.
Sorting should be descending by profit.
interface Job {
id: string;
deadline: number;
profit: number;
}
const jobs: Job[] = [
{ id: 'a', deadline: 2, profit: 100 },
{ id: 'b', deadline: 1, profit: 19 },
{ id: 'c', deadline: 2, profit: 27 }
];
function scheduleJobs(jobs: Job[]): string {
jobs.sort((a, b) => b.profit - a.profit);
const n = jobs.length;
const result: (string | null)[] = Array(n).fill(null);
const slot: boolean[] = Array(n).fill(false);
for (let i = 0; i < n; i++) {
for (let j = Math.min(n - 1, jobs[i].deadline - 1); j >= 0; j--) {
if (!slot[j]) {
slot[j] = true;
result[j] = jobs[i].id;
break;
}
}
}
return result.filter(x => x !== null).join(' -> ') + ' -> null';
}TypeScript allows optional semicolons but missing semicolon after slot[j] = true can cause issues in some cases.
Other options are valid TypeScript syntax.
Sorted by profit: j4(100), j2(80), j1(70), j5(40), j3(30), j6(20).
Assign j4 to slot 1 (deadline 2), j2 to slot 0 (deadline 1), j5 to slot 2 (deadline 3), j1 to slot 3 (deadline 4).
Slots 0 to 3 correspond to time 1 to 4.
Schedule is "j4 -> j2 -> j5 -> j1 -> null".