Animate the Job Sequencing with Deadlines algorithm. See how sorting by profit and assigning each job to the latest available slot maximizes total profit.
About this algorithm
Job sequencing picks which jobs to run when each job takes one unit of time, has a deadline, and pays a profit only if it finishes by that deadline. Only one job can run at a time, so some jobs have to be turned down. The greedy method takes jobs from the most profitable down and places each one in the latest free time slot that still meets its deadline.
Use it for scheduling problems shaped like this one: equal-length tasks, hard deadlines, a reward per task, one worker or machine. Examples are ad slots that must air before a date, or assignments each worth some marks and due on a given day. If the tasks have fixed start and end times and you want to fit as many as possible, that is activity selection instead. If tasks have different lengths and a value each, the problem becomes a form of 0/1 knapsack and greedy no longer guarantees the best answer; dynamic programming does.
The most valuable job gets the first claim on a time slot.
Make as many empty slots as the largest deadline. Slot t covers the time from t - 1 to t, so a job with deadline 2 can use slot 1 or slot 2.
For the next job, look at the slot equal to its deadline and walk backwards to slot 1, taking the first empty one. Putting it as late as possible keeps the early slots open for jobs whose deadlines are tighter.
If every slot up to its deadline is taken, skip the job. When every job has been tried, add up the profits of the scheduled ones.
The page loads J1 (deadline 2, profit 100), J2 (1, 19), J3 (2, 27), J4 (1, 25) and J5 (3, 15). By profit the order is J1, J3, J4, J2, J5, and the largest deadline is 3, so there are three slots. J1 takes slot 2, the latest one its deadline allows. J3 also has deadline 2; slot 2 is full, so it steps back to slot 1. J4 must finish by time 1, but slot 1 is taken, so it is rejected, and J2 is rejected for the same reason. J5 has deadline 3 and slot 3 is free. The schedule is J3, J1, J5 in slots 1 to 3, for a total profit of 27 + 100 + 15 = 142.
Take two jobs: A with deadline 2 and profit 50, and B with deadline 1 and profit 40. A comes first by profit. Put it in the earliest slot, slot 1, and B has nowhere to go: total 50. Put A in slot 2 instead and B fits in slot 1: total 90. Filling from the deadline backwards never blocks a job that could have fitted.
Time: sorting costs n log n, and each of the n jobs may walk back through up to d slots, where d is the largest deadline; a disjoint-set structure that jumps straight to the latest free slot brings that part close to linear. Space: one slot per time unit up to the largest deadline d, plus the sorted list of jobs.