Maximize profit by scheduling jobs with deadlines greedily. Sort jobs by profit descending, then assign each job to the latest available slot before its deadline.
Job sequencing with deadlines is a greedy algorithm that maximizes profit by scheduling jobs optimally. Each job has a deadline and profit; a job cannot be started after its deadline. The key insight is to process jobs in decreasing order of profit and place each job in the latest available time slot before its deadline.
1. Sort by Profit: Arrange jobs in decreasing order of profit. Ensures highest-value jobs are considered first.
2. Backward Scheduling: For each job, search backward from (deadline - 1) to 0 to find the latest available slot.
3. Slot Assignment: If a free slot exists before the deadline, assign the job there. Otherwise, skip the job (no capacity).
4. Feasibility: This order ensures maximum flexibility — by placing jobs late, we leave early slots for lower-profit jobs.
5. Optimality: Greedy choice of maximum profit first guarantees globally optimal solution for this problem.
Job Schedule State
Sorted by Profit (Descending)
Press 'Solve Greedy'
Maximum Profit Schedule
Jobs Input
| Job | Profit | Deadline | Status |
|---|---|---|---|
| J1 | 60 | 2 | — |
| J2 | 100 | 3 | — |
| J3 | 80 | 2 | — |
| J4 | 70 | 3 | — |
| J5 | 50 | 1 | — |
Pseudocode
id, profit, deadline — plus maxDeadline
Algorithm & Implementation
1. Job Structure (lines 3-5): typedef struct with id, profit (gain), and deadline (latest time). Encapsulates all job data for sorting and scheduling.
2. Compare Function (lines 7-9): Comparator for qsort() sorting jobs in descending profit order: ((Job*)b)->profit - ((Job*)a)->profit. Ensures highest-profit jobs processed first, greedy choice.
3. Slot Array (lines 13-14): Represents time slots 0 to maxDeadline-1. slot[j] stores job ID scheduled at slot j, initialized to -1 (empty). Each index = one unit of time.
4. Backward Scheduling (lines 17-24): For each sorted job: iterate backward from (deadline-1) to 0. If slot[j] == -1 (empty), place job and break. Backward search ensures latest available slot used, maximizing flexibility for remaining jobs. If no slot available, skip job.
5. Time Complexity O(n² + n log n): qsort() is O(n log n). For each of n jobs, search backward through up to maxDeadline slots: O(n × maxDeadline) = O(n²) worst case. Total: O(n log n + n²) ≈ O(n²). Space O(maxDeadline) for slot array.