Activity selection and fractional knapsack
Three classic greedy algorithms with their proofs: activity selection (earliest finish first, why earliest start and shortest first fail), the fractional knapsack (best value per unit weight first, why the same rule fails for 0/1 knapsack), and job sequencing with deadlines and profits; also interval partitioning (minimum number of rooms equals the maximum overlap). Running times and worked GATE-style instances.
Why it exists
Three problems show what a correct greedy algorithm looks like, and one of them shows what happens when the same idea is applied where it does not work. Activity selection (schedule the most non-overlapping jobs) and the fractional knapsack (fill a bag with the most valuable cuttable goods) are solved exactly by a simple rule and a sort; the 0/1 knapsack (items cannot be cut) has the same rule and is not solved by it. GATE asks for the greedy rule, the running time, the selected set for a given instance, and why a plausible rule fails.
Prerequisites
You need the greedy-choice property and the exchange argument (greedy method).
Precise definitions
Activity selection. Activities , activity occupying the half-open time interval . Two activities are compatible if their intervals do not overlap (one may start exactly when the other finishes). Choose a largest set of mutually compatible activities.
Interval partitioning. The same activities must all be performed, each in a "room"; activities in one room may not overlap. Find the fewest rooms.
Fractional knapsack. A bag holds weight . Item has weight and value , and any fraction of an item may be taken (worth and weighing ). Maximise subject to .
0/1 knapsack. The same, but each item is taken completely or not at all ().
Job sequencing with deadlines. jobs, each needing one unit of time on one machine, job with a deadline (it must be finished at time or earlier, that is, started in one of the slots ) and a profit earned only if it meets its deadline. Choose and order jobs for maximum total profit.
How it works
Activity selection
Rule: sort by finish time; take the first activity; then repeatedly take the next activity that starts no earlier than the finish of the last chosen one. The animation runs the real code on nine activities already sorted by finish time: chosen ones turn green, rejected ones (overlapping the last chosen) fade.
Activity selection: always take the compatible activity that finishes first
Real runC source
Start s[i]
Finish f[i]
chosen[i] (1 = chosen, 0 = rejected)
State
Blue = the position this step is working on, amber = a position being compared, red = positions just swapped, green = finished or in its final place, a filled blue cell = a value just placed, faded = not part of the structure at this step.
Step 1
Nine activities, sorted by finish time. Choose as many mutually compatible (non-overlapping) activities as possible.
Why earliest finish. Choosing the activity that finishes first leaves the largest possible remaining time. Proof (exchange). Let be the activity with the earliest finish time and any optimal solution, with first activity (in the order of finish). Since and everything else in starts at or after , replacing by keeps compatible and of the same size: an optimal solution contains . What remains is the same problem on the activities that start at or after (optimal substructure), so by induction the greedy algorithm is optimal.
Other plausible rules fail. Each of them was tried against the exact optimum (found by trying all subsets).
Three greedy rules for activity selection: start
Computed by a script, not typed| rule | instance 1: A(0,10) B(1,2) C(3,4) | instance 2: A(0,5) B(4,6) C(5,10) | verdict |
|---|---|---|---|
| earliest start first | |||
| shortest first | |||
| earliest finish first |
Step 0
Activities are chosen in the order of a rule, skipping any that overlaps one already chosen. Only the rule 'earliest finish first' is optimal; the other two fail on one of these two small instances. The optimum is found by trying every subset.
Earliest start first is blocked by one long activity; shortest first can pick a short activity in the middle that overlaps two others; fewest conflicts first also fails (a counterexample with at most eleven activities was found by search). Only earliest finish first is right.
Running time. Sorting by finish time: ; the single scan afterwards: . If the activities are already sorted the algorithm is .
Interval partitioning. Sort the activities by start time; give each to any room that is free, opening a new room only when all are busy. The number of rooms equals the maximum number of activities running at the same time (the depth): it is at least that (all of those need different rooms) and the algorithm never opens a room unless that many are running. Time .
Fractional knapsack
Rule: sort the items by value per unit weight, largest first; take whole items while they fit; take a fraction of the first item that does not fit; stop. The animation fills a bag of units with four items of ratios .
Fractional knapsack: fill the bag with the best value per unit weight first
Real runC source
Weight w[i]
Value v[i]
Value per unit weight
Weight taken
State
Blue = the position this step is working on, amber = a position being compared, red = positions just swapped, green = finished or in its final place, a filled blue cell = a value just placed, faded = not part of the structure at this step.
Step 1
Four items and a bag that holds 30 units. Items may be cut: any fraction of an item can be taken.
Why it is optimal. Suppose an optimal filling takes some of an item with a lower ratio while a higher-ratio item is not fully taken. Remove a little weight of the lower-ratio item and add the same weight of the higher-ratio one: the weight is unchanged and the value rises by . So no optimal solution can contain such a pair, and the greedy filling (which has no such pair) is optimal. The result was also confirmed against an exact linear programming search on random instances.
Running time. for the sort, then . (A selection algorithm for the item at the critical ratio makes it in all.)
The 0/1 knapsack is different. With items of weight and value and capacity the ratios are . The same rule takes the first two items (weight , value ) and cannot fit the third; but the items and together (weight ) are worth . The exchange argument fails because a fraction cannot be moved: the leftover capacity is wasted. The 0/1 knapsack has no known polynomial-time greedy algorithm; it is solved by dynamic programming in time (dynamic programming problems), which is pseudo-polynomial.
Job sequencing with deadlines
Rule: consider the jobs in order of decreasing profit; put each into the latest free time slot not after its deadline; if there is none, reject it. The table runs it on six jobs.
Job sequencing with deadlines (unit-time jobs): start
Computed by a script, not typed| job (in order of decreasing profit) | deadline | profit | decision | slots 1, 2, 3 | total profit so far |
|---|---|---|---|---|---|
| job a | |||||
| job c | |||||
| job d | |||||
| job b | |||||
| job e | |||||
| job f |
Step 0
Each job takes one time unit and must finish by its deadline. Jobs are considered in the order of decreasing profit and put in the latest free slot not after the deadline. The final total is checked against an exhaustive search over all subsets of jobs.
Why it works. A set of jobs can all be scheduled exactly when, for every , at most of the jobs have deadline or earlier (they must all fit into the slots ). Placing a job in the latest free slot keeps the early slots open for jobs with early deadlines; processing by profit makes the accepted set a maximum-profit feasible set (the feasible sets form a matroid, for which greedy by weight is optimal). The result for the table was checked against an exhaustive search over all subsets.
Running time. With a simple search for the latest free slot: (for each job scan down from its deadline). With a disjoint-set structure for free slots: nearly (the sort dominates).
Worked examples
EX 1Activity selection by hand
EasyActivities : , already sorted by finish. Take . starts at : reject. : reject. starts at : take; last finish . : reject. : reject. : reject. : take. Chosen: : three activities. If the list is not sorted by finish time, sort first.
EX 2Fractional knapsack by hand
EasyCapacity ; items (weight, value): ; ratios . Take the first completely (weight , value ), the second completely (weight , value ), and of the units of the third: value . Total . The 0/1 optimum for the same data is , so allowing cuts gains .
EX 3Job sequencing
MediumJobs (deadline, profit): . By decreasing profit: goes to slot ; to slot ; wants slot (taken) and gets slot ; wants slot (taken): rejected; wants : all taken, rejected; rejected. Schedule: slot : , slot : , slot : . Profit . Check: would give , and no feasible set is better (exhaustive search).
EX 4Minimum number of rooms
MediumLectures . At time three are running: , so at least rooms. Sorted by start, greedy assigns: , , , (free at ), (free at ). Three rooms, equal to the maximum depth.
EX 5Which rule, what time?
GATE level(a) Activity selection with unsorted activities: . (b) Fractional knapsack with items: ; 0/1 knapsack greedy by ratio: not optimal; 0/1 knapsack: by dynamic programming. (c) Maximum number of activities compatible when activities are given: (the first three; touching intervals are compatible). (d) Job sequencing, jobs, naive implementation: . (e) A greedy algorithm that picks the activity with the smallest duration: not always optimal.
Cheat box
Cheat box
- Activity selection: sort by finish time, take every activity that starts at or after the last chosen finish. . Optimal by exchange. Earliest start, shortest, fewest conflicts: wrong.
- Interval partitioning: sort by start; rooms needed = maximum overlap (depth).
- Fractional knapsack: sort by value/weight, take whole items, then a fraction. . Optimal. 0/1 knapsack: greedy by ratio is not optimal; DP .
- Job sequencing: decreasing profit, latest free slot deadline; feasible set iff at most jobs have deadline for every ; naive.
- Compatible means (touching allowed).
Traps and GATE patterns
Connections
Builds on
Across subjects
No cross-subject links yet.
All three rely on the exchange argument of the greedy method. The 0/1 knapsack and its dynamic programming solution are in dynamic programming problems. The same style of greedy choice, always merge the two smallest, builds Huffman codes.
PYQs
2 previous year questions from your book. I re-solved each one myself (2 by running or simulating, 0 by reasoning only); the book's key is shown next to my answer. All PYQs
We are given 9 tasks T1, T2... T9. The execution of each task requires one unit of time. We can execute one task at a time. Each task Ti has a profit Pi and a deadline di Profit Pi is earned if the task is completed before the end of the d th unit of time. What is the maximum profit earned?
- (a)147
- (b)165
- (c)167
- (d)175
We are given 9 tasks T1, T2... T9. The execution of each task requires one unit of time. We can execute one task at a time. Each task Ti has a profit Pi and a deadline di Profit Pi is earned if the task is completed before the end of the d th unit of time. Are all tasks completed in the schedule that gives maximum profit?
- (a)All tasks are completed
- (b)T1 and T6 are left out
- (c)T1 and T8 are left out
- (d)T4 and T6 are left out
Self-check
Question 1
Activities : how many can be chosen and which?
Show answerHide
Two: and (touching is allowed); the greedy then rejects , takes and rejects . Also possible: .
Question 2
Fractional knapsack, capacity , items (weight, value) . What is the maximum value?
Show answerHide
Ratios : take items and (), value .
Question 3
Why does greedy by value per weight fail for 0/1 knapsack?
Show answerHide
Leftover capacity cannot be filled by a fraction of an item; a combination with a lower-ratio item can use the capacity better (for example with capacity : greedy , optimum ).
Question 4
How many rooms does the interval-partitioning greedy use for a set of lectures (give it in terms of the lectures' overlaps)?
Show answerHide
The maximum number of lectures that run at the same time.
Revision card
One-screen revision
- Activity selection: earliest finish first, , exchange proof; other rules fail.
- Rooms = maximum overlap (sort by start).
- Fractional knapsack: value/weight descending, one fraction at the end, optimal; 0/1: not greedy, DP .
- Job sequencing: profit descending, latest free slot; .
References
- ·Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (3rd edition), Chapter 16 Greedy Algorithms (16.1 an activity-selection problem, 16.2 the fractional knapsack problem)
- ·Kleinberg and Tardos, Algorithm Design, Chapter 4 (4.1 interval scheduling, 4.1 interval partitioning)
- ·Horowitz, Sahni, Rajasekaran, Fundamentals of Computer Algorithms, Chapter 4 The Greedy Method (job sequencing with deadlines)
Verification
Activity selection by earliest finish equalled the brute-force optimum on 3000 random instances (n up to 8), while earliest start first and shortest first failed (small instances found by search, shown on the page) and the fewest-conflicts rule also failed on a random instance found by search. Interval partitioning used exactly the maximum overlap on 500 random instances. The greedy fractional knapsack value equalled the exact linear programming optimum, computed by enumerating every vertex, on 500 random instances; the 0/1 knapsack counterexample and the animation total (194) were recomputed. Job sequencing by profit with the latest free slot equalled an exhaustive optimum on 1500 random instances, and the feasibility test (for every t at most t jobs have deadline t or less) agreed with trying every order. The two animations are real runs of the C code shown. Job sequencing is not in the official GATE list but appears in textbooks and past papers; its running times are the standard ones. Textbook chapter references are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand or by a small script (loop counts, recurrences, merge and quicksort counts and averages, hash probes and load-factor formulas, DP tables, MST and shortest-path runs, Floyd matrices); long C programs were not re-read line by line (they are compiled and compared by npm run verify:c, and their printed outputs were checked against the prose); tables and animations are machine output and were read, not re-run; One Self-check question about the number of rooms was reworded because 'at most' was ambiguous. Status raised to self-checked; verified needs a textbook or human check.
last verified: never
My notes (saved in this browser)