Skip to main content
Artificial Computational Intelligence

Greedy Method

Published: 2026-08-09
Level: postgraduate
Audience: Postgraduate students studying algorithm design techniques

The course changes mode here. The first half was spent on data structures and abstract data types (ADTs) — stack, queue, list, position, heap, binary tree, binary search tree, dictionary, and vector. Those structures do not disappear; we keep using them. But from this point on, the discussion centers on algorithm design techniques — general strategies for designing algorithms that can be applied to many different problems. The first such technique, and the topic of this session in full, is the greedy method.

This session follows the greedy method from its everyday roots to its classic problems. We start by seeing greedy thinking emerge from a bank cashier's coin problem, then formalize it with configurations, objective functions, and the greedy choice property. Real-life examples show where the strategy appears naturally. Then come three classic problems solved greedily: the fractional knapsack, ship loading, and job sequencing with deadlines. A full exam-style problem ties the method together, and the session closes with the textbook's application list plus the exam guidance given at the start of the class.

8.1 Algorithm Design Techniques — the Course Pivot

8.1.1 From Data Structures to Design Techniques

A quick recall exercise opened the session: which ADTs had we already covered? The answers came fast — stack, queue, list, dictionary, position, heap, binary tree, binary search tree, vector. The response to the list was an emphatic "all linear ADTs we discussed," and the tree structures we built on top of them. That was the whole first half of the course in one breath.

The second half starts with a deliberate change of focus. Instead of asking "what data structure fits this problem," we ask "how do we design the algorithm itself." The data structures remain in the toolbox — they get used again here — but the discussion now leads with design.

Hook — why change focus now? A data structure tells you how to store data, but storing data is only half of computing. The other half is the procedure that turns stored data into an answer — and that procedure is the algorithm. The first half of the course handed you a well-stocked toolbox: stacks, queues, heaps, trees, dictionaries. This half teaches you how to think about building the algorithms that use those tools.

The distinction shows up in exam questions too: a question that asks "which data structure" and a question that asks "how would you design an algorithm" are different questions, and the course now trains the second one.

8.1.2 What Is an Algorithm Design Technique?

The instructor asked the class to define the term before explaining it. The guesses were telling.

Q: What do you understand from the term "algorithm design technique"? Is it an algorithm? A: One student said "optimized and giving minimum time complexity." That answer is off target — a design technique has nothing in particular to do with time complexity. Another said "path to problem solving," which was agreed with. "Deciding which ADT to use" is not quite it either. The useful answer is "an approach to planning an algorithm." An algorithm design technique is a general approach to solve problems algorithmically, and a single technique lets you solve a wide variety of problems. It is not one specific algorithm.

Algorithm design technique (the definition): a general approach to solving problems algorithmically — a template for thinking, not a particular algorithm and not a particular data structure. One technique can be applied to problems you have never seen before, and a single technique gives rise to many different algorithms.

The key idea: a design technique does not name a particular algorithm or a particular data structure. It is a way of thinking about problems, a template that you can apply to problems you have never seen before.

A technique differs from an algorithm the way a cooking style differs from a recipe. "Frying" is a technique: you can fry eggs, fish, vegetables, or cutlets, and each of those is a different recipe. A single recipe — "fried egg, sunny side up" — is a specific algorithm: exact ingredients, exact steps, one dish. The greedy method is a technique; a greedy algorithm for a specific problem is a recipe built from that technique.

8.1.3 The Hand-Tool Analogy

To make the idea concrete, the instructor used carpentry. A furniture workshop has two kinds of tools. There are specialized power tools — say, a machine designed to make sofa parts or table parts. For the one kind of furniture it is built for, that tool produces parts with utmost perfection. But it is not versatile; it cannot do anything else. Then there are general-purpose hand tools — hammer, saw, screwdriver. No hand tool makes a finished piece of furniture by itself, but with the know-how to use them, a carpenter can build any kind of furniture with hand tools.

The specialized power tool is a specific algorithm, good for the problem it was designed for. The hand tool is the algorithm design technique: fundamental, general, and applicable to a wide range of problems once you know how to drive it. The design technique is exactly that kind of tool — not a specialized solution, but a general approach.

Carpentry Algorithms
Specialized power tool (a machine that makes sofa parts) A specific algorithm built for one problem
Makes that one part perfectly, nothing else Solves that one problem, nothing else
General-purpose hand tool (hammer, saw, screwdriver) An algorithm design technique
No hand tool alone makes furniture No technique alone is an algorithm
With know-how, hand tools build any furniture With know-how, a technique designs algorithms for many problems

Visual intuition — the workshop shelf. Picture a workshop wall. On one side stand special-purpose machines, each bolted down and dedicated to one product line: this one stamps sofa arms, that one cuts table legs. The machines sit idle for anything outside their one job. On the other side hangs a small rack of hand tools — hammer, saw, screwdriver, plane. The hand tools follow the carpenter to every job in the shop. The syllabus for this course is the hand-tool rack: a few techniques, each of which follows you to many problems.

Recap and bridge: an algorithm design technique is a general approach to designing algorithms — the hand tool, not the power tool. The techniques on the syllabus for this course: greedy method, divide and conquer, and dynamic programming. This session goes through the greedy method in detail. The instructor stressed twice: it is not exactly an algorithm; it is a design technique. The next section meets greedy the way the class met it — through the change-making problem, where the strategy appears by itself before anyone names it.

8.2 The Change-Making Problem — Greedy Thinking by Example

The best way to meet the greedy method is through the change-making problem — the one bank cashiers face most of the time. For simplicity, the examples use paise as the unit.

8.2.1 First Example: Change for 32 Paise

The denominations available to the cashier are 25, 10, 5, and 1 paise. The cashier's till holds one 25-paise coin, two 10-paise coins, two 5-paise coins, and five 1-paise coins. The task: give change for 32 paise.

The class produced two answers: 25 + 5 + 1 + 1 (four coins) and 10 + 10 + 5 + 5 + 1 + 1 (six coins).

Q: What made you give the answer 25, 5, 1, 1? A: Because 25 is less than 32, give 25 first. The aim is the minimum number of coins — this is the optimization objective. Your greedy thinking is exactly what made you give this answer.

The greedy reasoning, step by step:

  • Look for the largest denomination that does not exceed 32. That is 25. Give the 25-paise coin.
  • The remaining problem shrinks to 7 paise. The largest denomination that fits in 7 is 5. Give the 5-paise coin.
  • The remaining problem shrinks to 2 paise. Give two 1-paise coins.

So the greedy answer is , four coins total. The big problem (32 paise) was reduced to a small one (7 paise) in one step, and then to 2 paise. Each step takes the largest coin that can possibly be given, without thinking about the future.

Worked example — change for 32 paise. The till holds one 25-paise coin, two 10-paise coins, two 5-paise coins, and five 1-paise coins.

  1. Target 32. The largest coin that fits in 32 is the 25-paise coin: give it. Amount left: paise.
  2. Target 7. The largest coin that fits in 7 is the 5-paise coin: give it. Amount left: paise.
  3. Target 2. The largest coin that fits in 2 is the 1-paise coin: give it, and again — two 1-paise coins. Amount left: 0.

The greedy answer is 25 + 5 + 1 + 1 = 32 paise, using 4 coins. The till has exactly these coins: one 25-paise coin, one 5-paise coin, and two 1-paise coins — no coin runs out. Sense-check: every coin used is legal, the total is exactly 32, and the count (4) beats the other answer the class produced (six coins). Since the objective is the fewest coins, greedy found the optimum here.

This answer is also the optimal solution — it uses the fewest possible coins. The objective was to minimize the number of coins, and greedy happened to achieve it here. That is why the instructor called it "one of the most correct answers."

Visual intuition — the shrinking target. Picture the amount as a line of 32 small marks. Each greedy step draws one coin across the largest chunk it can cover: the 25-paise coin wipes out marks 8 to 32, the 5-paise coin covers marks 3 to 7, and two 1-paise coins cover the last two marks. The line empties from the right, always taking the longest single span available. That is the whole strategy in one picture: cover as much as possible now, then look again at what is left.

8.2.2 Second Example: Change for 20 Paise — Greedy Fails

Same kind of problem, different coin set. Available: one 15-paise coin, two 10-paise coins, and five 1-paise coins. Change for 20 paise.

Worked example — change for 20 paise, greedy vs optimal. The till holds one 15-paise coin, two 10-paise coins, and five 1-paise coins.

Greedy run: the largest coin that fits in 20 is 15 — give it. Amount left: paise. The largest coin that fits in 5 is the 1-paise coin, so give five 1-paise coins. Total: 1 × 15 + 5 × 1 = 6 coins.

Optimal run: two 10-paise coins give with 2 coins. No single coin equals 20, so at least two coins are needed — and the two 10-paise coins achieve that bound.

So greedy uses 6 coins where the optimum uses 2. The greedy answer is a valid answer — the change adds up correctly — but it is not the best answer.

The optimal solution is different: two 10-paise coins — two coins.

Greedy picked 15 first because giving 15 reduces the problem at hand to the maximum. It never asked whether that choice leads to an optimal final answer. It did not. So in this second example, greedy thinking does not give the optimal solution.

This is the moment to be careful: in the first example greedy produced an optimal solution; in the second it did not. Greedy thinking will not guarantee an optimal solution. It will always give you a solution — but that solution may not be optimal. Greedy gives the optimal answer only when the problem has the greedy choice property (next section). This second problem lacks it: the optimal solution to the subproblem "give change for 15 paise" would be a single 15-paise coin, and that 15-paise coin is never part of the optimal solution for 20 paise. The optimal solution of the big problem does not contain the optimal solution of the subproblem.

Warning — why the greedy choice backfired here. At the first step greedy had a choice between a 15-paise coin and a 10-paise coin. Locally, 15 "eliminates more problem" than 10 — it leaves only 5 paise instead of 10. But that local win destroys the global optimum: after taking 15, no coin can finish the job efficiently, while taking 10 leaves room for a second 10. The choice looked best right now and was wrong for the final answer. Once the 15-paise coin is handed over, the mistake cannot be undone — which is why the irrevocability of greedy choices (Section 8.3.4) matters.

Exam note: the change-making problem is the model for exam questions of the optimization type. The two examples teach the pair of facts you will be expected to state: greedy gives a solution always, and the optimum only when the greedy choice property holds.

8.2.3 Student Questions on the Coin Problems

Q: For 25 paise, we could give one 25-paise coin. Or we could give two 10-paise coins plus a 5-paise coin. Which is right? A: The first is optimal — one coin beats three. Greedy would pick the 25-paise coin first, and it would be right here.

The same question, asked about any amount, gets the same answer — the rule never changes:

Q: How would greedy solve for any amount, say 21 paise? A: The same way every time: give the largest denomination that fits, then solve the remaining amount the same way. The denominations in these examples are fixed; the method is to always return the largest coin you can.

Pitfall — believing greedy is always optimal. The 32-paise example makes greedy look flawless; the 20-paise example is the counterexample that must stay in your head. Any time you apply the strategy, the answer needs a check: does this problem have the greedy choice property? Without that check, a greedy answer is a candidate, not a proof.

Real-world: this is the exact problem a bank cashier or a vending machine solves dozens of times a day. The point of the two examples is that the same strategy that feels natural to a human (take the biggest coin that works, then repeat) is the greedy method — and it has a flaw that only the greedy choice property can patch.

Recap and bridge: greedy thinking is "always return the largest coin you can" — a strategy that solved 32 paise optimally and failed on 20 paise. Whether it works depends on a property of the problem, not of the strategy. Next we give the method its formal shape — configurations, objective functions, and the greedy choice property that separates the problems greedy can solve from the ones it cannot.

8.3 Greedy Method — Definition and Properties

8.3.1 Configurations and Objective Functions

The formal definition: a greedy method is a general algorithm design paradigm built on two ideas — configurations and an objective function.

Configuration (what we build): the different choices, collections, or values we can form in a problem. For the coin problem: the configuration is the dollar amount yet to return to the customer plus the coins already returned — in other words, the exact multiset of coins you are handing over. Every different way of making 20 paise is a different configuration.

Objective function (the score): a score assigned to a configuration, which we want to either maximize or minimize. In the coin problem the score is the number of coins, and we minimize it. A problem that asks you to maximize or minimize some value is an optimization problem — the coin problem is one, and so are both knapsack problems later in this session.

For 20 paise with the 15/10/1 till, two configurations exist: one 15-paise coin plus five 1-paise coins (score 6), and two 10-paise coins (score 2). The objective function is the count of coins, and the optimization problem is to find the configuration with the minimum count. If stands for the number of coins in a configuration, the objective is

and the answer is the configuration that reaches that minimum.

The greedy thinking for the coin problem, in one sentence: always return the largest coin you can. For the first example's coins (25, 10, 5, 1), this works optimally. The intuition behind the strategy: each step should eliminate as much of the remaining problem as possible, so pick the biggest denomination that still fits. Greedy never asks whether today's choice is good for the final answer — it only asks what looks best right now.

Here is the casual way to think of the method: it is a design strategy that tries to find the best solution for each subproblem, with the hope that this will yield a good solution for the problem as a whole. When you first meet a problem, you solve the maximum possible from it right away. You do not know whether the path you are on now leads to the best solution — you take whatever looks best at this particular point. The method makes a choice that looks best at the moment without worrying about the effect that choice has in the future. In the 20-paise example, giving the 15-paise coin was the locally best move — it shrank the problem the most — and it was exactly the move that ruined the outcome.

Once a choice is made, it cannot be reversed. That irreversibility is what locks in the suboptimal outcome in the 20-paise example.

To solve a problem with a greedy method, you proceed by a sequence of choices: start from some well-understood starting configuration, then iteratively make the decision that seems best at present, until the problem is solved. This sequence will not always lead to an optimal solution; it works optimally exactly for problems with the greedy choice property.

8.3.2 Greedy Choice Property

The greedy choice property is the property that makes the greedy method trustworthy: a globally optimal solution can be arrived at by making locally optimal choices. When a locally optimal choice can lead to a globally optimal solution, the problem has this property.

Greedy choice property (definition): the property a problem has when a globally optimal solution can be reached by a series of locally optimal choices. "Locally optimal" means best among the options available at this step; "globally optimal" means the best possible solution to the whole problem. When the property holds, the greedy sequence of choices is guaranteed to end at the optimum. When it does not hold, greedy may still give an answer — just not the best one.

It is not easy to look at a problem and know whether it has the property. You cannot tell just by inspection — you have to work it out. The instructor showed this with two coin sets.

Coin set {32, 8, 1} — the property holds. Suppose the change due is 40 paise. Greedy picks the largest coin that fits: 32. The remainder is , and the largest coin that fits in 8 is 8. The greedy answer is 32 + 8 = 40 paise with 2 coins, and that is also optimal: no single coin in {32, 8, 1} equals 40 (the largest is 32, which is less than 40), so any solution needs at least 2 coins, and greedy achieves that minimum. Here the locally optimal first move (32) stays inside a globally optimal solution, which is exactly the greedy choice property. In the instructor's words, this set has the property because no amount over 32 can be made with a minimum number of coins by omitting a 32.

Coin set {30, 25, 1} — the property fails. The slide states that the coins are valued 30, 25, and 1, and the instructor's walkthrough makes the check concrete (the optimal answer he describes uses two 20-paise coins, so the till must also hold 20s; and greedy hands out 5s for the remainder, so 5-paise coins exist too). For change of 40 paise:

  • Greedy: the largest coin that fits in 40 is 30. The remainder is 10 paise, so greedy gives two 5-paise coins. Total: 30 + 5 + 5 = 40 paise with 3 coins.
  • Optimal: 20 + 20 = 40 paise with 2 coins.

Greedy needs three coins where the optimum needs two. The greedy first move (30) is locally reasonable — it covers the most value in one coin — but the optimal solution of the big problem never uses a 30-paise coin. Since the greedy choice is not part of any optimal solution, the problem lacks the greedy choice property.

The instructor's answer to the earlier question about greedy for arbitrary amounts used this same 40-paise example: greedy gives one 30-paise coin first; the remaining problem is change for 10 paise; greedy gives what fits (described in class as giving 5s), landing on three coins total, while the optimal solution solves the same problem with two coins.

So the check is problem-dependent. You may have to look at the coin values and work out whether the greedy choice stays inside some optimal solution. There is no formula that tells you in advance.

Scope — how the check works. The only general way to test a coin system is to compare greedy with the optimum on the amounts that could be hard. The pattern to watch for is a coin that greedy skips over — like 20, which is never greedy's first pick once 30 exists. There is no formula that tells you in advance whether the property holds; you have to work it out per problem. That is why the course pairs greedy with known problem families whose optimality has already been established, instead of guessing.

8.3.3 Optimal Substructure

The second property — optimal substructure — was introduced conceptually and flagged as the "second part" of the greedy story, to be developed later in the course. The concept: an optimal solution to a problem contains optimal solutions to its subproblems. The 20-paise problem shows what happens when it fails: the optimal solution to the subproblem "change for 15 paise" is one 15-paise coin, but that coin is not part of the optimal solution for 20 paise. The big optimal solution does not contain the subproblem's optimal solution, so the greedy approach built on that subproblem collapses.

Optimal substructure (definition): an optimal solution to a problem is built from optimal solutions to its subproblems. If the best answer to the big problem always contains the best answer to each smaller piece, the problem has optimal substructure. The greedy choice property and optimal substructure are the two conditions that make the greedy method trustworthy — the property says the locally best move is safe, and substructure says the rest of the problem after that move can still be solved optimally.

The two properties travel together in every greedy success story. The greedy choice property makes the first move safe; optimal substructure guarantees that the smaller problem left behind is worth solving greedily in turn. Both are needed — the 20-paise coin problem fails on both counts: greedy's first move (15) is not part of any optimum, and the optimal solution of the big problem does not contain the optimal solution of the subproblem.

Hold the greedy choice property firmly in mind: a problem must have it for the greedy strategy to give an optimal answer.

8.3.4 The Three Properties of a Greedy Choice

Every choice the greedy method makes must satisfy three conditions.

  1. Feasible — the choice must be possible: it has to satisfy the problem's constraints. You must be able to do it.
  2. Locally optimal — the choice must be the best solution you can make at the present step.
  3. Irrevocable — once made, the choice cannot be changed in subsequent steps.

Pitfall — choices are final. The three conditions act as a filter on every greedy step: reject moves that violate a constraint (not feasible), reject moves that are not the best available (not locally optimal), and understand that the chosen move is locked in forever (irrevocable). In the 20-paise problem, handing over the 15-paise coin passed the feasibility test and the local-optimality test, and the irrevocability of that move is exactly what sealed the suboptimal outcome — the cashier cannot ask for the coin back. When you design a greedy algorithm, check every step against all three conditions.

That is the whole method: take the best feasible option available, commit to it forever, repeat. It is an easy method to run — you stop worrying about the global optimum and just take the best available step. The difficulty lives entirely in deciding whether the problem deserves a greedy method at all.

8.3.5 Recognizing Greedy Problems

Q: How do we make sure that a problem has the greedy choice property? A: You have to solve it and find out — there is no other way. You solve the problem with greedy, then you prove that the greedy solution is optimal. That proof is what establishes the greedy choice property for your problem.

A second question followed naturally — whether the method must be applied by trial and error:

Q: Does greedy have to be applied in a trial-and-error fashion? A: No. There are standard problems that are already proved to be solvable with greedy — people smarter than us did those proofs. When you meet a new problem, you compare it with one of the known greedy problems; if it is similar in kind, apply greedy, then prove optimality for your specific problem.

Yes, this sounds awkward: if you must solve first and prove later, what is the use of the method? The answer is that applying greedy is very direct and very easy — the proof work is one-time, per problem family — and that is why greedy still finds use in many places.

Recap and bridge: the greedy method is built on configurations and an objective function; it works by a sequence of feasible, locally optimal, irrevocable choices; and it is guaranteed optimal exactly for problems with the greedy choice property and optimal substructure. Recognizing such problems is the real skill — you compare a new problem with known greedy problems, and the proof of optimality is done once per family. Next we look at where greedy thinking shows up in everyday life before the course's classic problems: knapsack, ship loading, and job sequencing.

8.4 Greedy Method in Real Life

8.4.1 Everyday Examples

Asked for real-life situations where the greedy strategy applies, the class produced a string of good answers.

Q: Give me some examples where this strategy can be used in real life. A: Preparing for an exam the night before. Your aim is to get more marks with less study in the remaining hours — maximize the marks gained per hour of study. That is an optimization problem, and greedy says: study the highest-yield topic first. A: Packing a vacation backpack. Also correct — you want the maximum value of items that fit the bag's weight limit, and the natural strategy is to pack the highest value-per-weight item first.

The exam-preparation example maps onto the greedy pattern cleanly. The configuration is your study plan; the objective function is marks gained per hour; the greedy choice is the highest-yield topic next; and the choice is irrevocable in the sense that the hours spent are gone. The backpack maps the same way: the configuration is the set of packed items, the objective is total value under the weight limit, and greedy packs the item with the best value-per-weight next.

8.4.2 Portfolio Optimization and Cutting Stock

Portfolio optimization is a rich real-world greedy application. A portfolio is the range of investments held by a person or an organization. Portfolio optimization is the process of selecting the best portfolio out of the set of all portfolios being considered, according to some objective — for example, the distribution of investment across sectors. The objective: maximize the factors you want (expected returns) while minimizing the factors you do not (financial risk). "Less risk, max profit" is the everyday phrasing. That is an optimization problem, and greedy is a natural candidate method.

Cutting stock problem comes from hardware factories. You have standard-size pieces of stock material — a paper roll, a sheet of metal — and you must cut them into pieces of specified sizes. The objective is to minimize the material wasted while fulfilling the order. Again: minimize something, so it is an optimization problem, and greedy-style cutting decisions are the standard approach.

Real-world: one more example surfaced from the class — the internet download manager. When you download a file, the data is broken into chunks, and the server packs the chunks according to the maximum size of data that can be retrieved in one go; the greedy algorithm packs the chunks so that the size limit is fully used on every request.

The takeaway the instructor left with the class: wherever you see maximize or minimize, you are looking at an optimization problem, and greedy should be the first option in your mind — at the very least, it gives you a starting point for where to apply greedy thinking. None of these everyday settings hands you a guarantee of optimality — but every one of them shows the greedy instinct at work, which is the first step of the method.

8.5 Fractional Knapsack

8.5.1 Problem Statement

First, the word: a knapsack is a bag or container — historically the bag soldiers carried back with them when they returned home. (Asked for the meaning, the class fell silent and someone went googling; the answer is simply "the bag.")

The problem: given a knapsack of capacity and objects with weights and profits associated with each object, place objects in the knapsack so that the profit is maximum and the total weight of the chosen objects does not exceed the capacity. The instructor's picture: a thief robbing a bank with a bag, packing objects so that profit is maximized within the bag's weight limit.

Fractional knapsack (the problem): pack a knapsack of capacity with objects , where object has weight and profit , so that the total profit is as large as possible and the total weight never exceeds . The word fractional matters: a fraction of an item may be taken. One-fourth of can be taken, or 0.5 of , or 0.35 of the third object. You are allowed to divide objects and take fractions. That is why this is the fractional knapsack problem. There is another variation, the 0/1 knapsack (take an object whole or not at all), which we study later, under a different method — not greedy.

The instructor noted that it has already been proved that this family of problems can be solved with the greedy method and yields an optimal solution here.

8.5.2 Mathematical Formulation

Let be the fraction of object that is added to the knapsack. The aim is to maximize profit:

"Summation of 1 to n, into — this will give me the maximum profit." Here is the profit associated with object , and is the fraction of that object taken.

The constraint: the weight of the chosen objects must not exceed the capacity.

" is the weight associated with each object and is a fraction of that object, so summation of 1 to n of should be less than or equal to capital , where is the capacity of the knapsack." Since is a fraction, it is bounded:

Maximize the profit; satisfy the capacity constraint at all times; that is the whole problem.

Every symbol has one job: is the number of objects; is the weight of object ; is the profit of object ; is the fraction of object taken; is the knapsack capacity. The fraction is the only decision variable — it runs from 0 (take nothing of object ) to 1 (take all of it), and values in between mean partial objects. The two equations together say: make the profit sum as big as possible, while the weight sum stays at or below . The same shape returns in ship loading (Section 8.6), with restricted to the two end values 0 and 1.

8.5.3 The Greedy Choice: Value per Unit Weight

The greedy choice: keep taking the item with the highest value. The word value is loaded — it means the profit-to-weight ratio:

Value is the profit obtainable per unit weight — per kg or per pound, as you prefer. Before applying the algorithm, compute for every object and arrange the objects in decreasing order of value. Then consider objects in that order.

Why does sorting by value make the method work? Because per-unit profit tells you how much profit each unit of weight brings. It is the number that lets you decide, later in the example, that taking all of object 3 is more profitable than taking a fraction of object 1. Without the value computation you could not make that decision.

Value (the greedy criterion): the profit per unit weight, , read "value of object is its profit divided by its weight." Think of it as the price tag per kilogram. Texts also call it the profit density or the value index; the idea is the same — a single number that ranks how "worth its weight" each object is. The greedy rule is then: take the object with the highest value next.

8.5.4 Worked Example: Three Gold Blocks

The knapsack capacity is (40 kg). There are three objects — the instructor imagined them as gold blocks:

  • Object 1: weight 20 kg, profit 30
  • Object 2: weight 25 kg, profit 40
  • Object 3: weight 10 kg, profit 35

Step 1 — compute values and sort. For each object, value :

  • Object 1:
  • Object 2:
  • Object 3:

So the objects must be considered in the order O3, O2, O1 — decreasing value. Considering them in any other order makes the solution wrong; the order is the whole point of step 1.

Step 2 — fill the table. The instructor's table method is the easiest way to run the algorithm; textbooks show other versions, but this table mirrors the algorithm exactly. Columns: object, weight , profit , fraction , profit earned , and remaining capacity (remaining capacity of the knapsack, initially ).

Object Weight Profit Fraction Profit earned Remaining capacity
O3 10 35 1 35 40 − 10 = 30
O2 25 40 1 40 30 − 25 = 5
O1 20 30 5/20 = 0.25 0.25 × 30 = 7.5 5 − 20 × 0.25 = 0

Object 3: weight 10, remaining capacity 40 — it fits completely, so , profit earned , and .

Object 2: weight 25, remaining capacity 30 — it also fits completely, , profit earned , and . (A student initially doubted this — that doubt is resolved in the Q&A below; the check is weight against capacity, never profit.)

Object 1: weight 20, remaining capacity 5. It does not fit. The fraction we can take is — one-fourth of the object, which makes sense: if an object weighs 20 kg and only 5 kg of space remains, one-fourth of it fits. Profit earned: . Remaining capacity: .

Final answer. The maximum profit is

Take object 3 completely, object 2 completely, and one-fourth of object 1 — total profit 82.5. The remaining capacity is 0 — the full capacity of the knapsack is utilized, and in the fractional knapsack that is always achievable. Sense-check: the bag weighs kg exactly, so nothing is wasted; and no other ordering can beat the best-ratio-first order, because every unit of weight is spent on the highest-value units available at the time.

Visual intuition — filling a box with gold. Picture the bag as a 40-kg box and each object as a block with its value per kg stamped on it. Greedy is a shopper who reads the stamps and drops the best-value block in first, then the next best, and when the last block does not fit, breaks off exactly the piece that fits. The box ends exactly full — in the fractional version there is always a piece size small enough to finish the job, which is why the final is a good self-check: the answer should always end at full capacity.

8.5.5 The Algorithm

The instructor emphasized: different textbooks show different versions of this algorithm, but this is the easiest version, and it matches the table above exactly. Keep the notation fixed: for weight, for profit, for the fraction, for remaining capacity.

1.  Arrange the objects in decreasing order of p_i / w_i
2.  for i = 1 to n:
3.      x_i = 0                      // fractions array, initialized
4.  RC = M                           // remaining capacity starts at the full capacity
5.  for i = 1 to n:
6.      if w_i > RC: break           // weight exceeds remaining capacity; nothing more fits
7.      x_i = 1                      // take the complete object
8.      RC = RC - w_i                // reduce remaining capacity
9.      P = P + p_i                  // add the full profit
10. if i <= n:                       // a fraction of the current object can still be taken
11.     x_i = RC / w_i
12.     P = P + x_i * p_i            // add the fraction's profit

Inputs and outputs of the algorithm. Input: objects, each with weight and profit , and the capacity . Output: the fraction taken of each object, and the total profit . The fraction array starts at all zeros; (remaining capacity) starts at ; accumulates the profit as objects are added. The packing loop makes the greedy choice one object at a time in the sorted order.

The logic in English: walk the objects in decreasing value. While the next object's weight fits in the remaining space, take it whole — every kilogram of a full object earns its value. The moment an object weighs more than what is left, stop taking whole objects and take only the fraction that exactly uses up the space, then finish. The break and the final fraction are the only two exits from the packing loop.

Walk through it against the example: the loop takes O3 (), then O2 (); at O1 the test triggers the break; the last if computes and adds . Exactly the table.

8.5.6 Time Complexity

The time complexity is — because of the sorting step. This is the step that everyone misses when computing the complexity. The loops themselves run in , and the if statement is ; the sorting is what dominates. The instructor used heap sort in the example because heap-based sorting is the only sorting we have studied so far, but any sorting algorithm works — it is not mandatory to use heap sort. Different sorting algorithms give different overall complexities, so use the sorting algorithm that does the job in the most effective way; several sorting algorithms run in , and more of them appear in the next algorithm design strategy.

Pitfall — quoting and forgetting the sort. The value computation, the fraction array initialization, and the packing loop each cost , and the fit test costs . But the whole algorithm is because step 1 sorts. The sort is the step that everyone misses when computing the complexity — and naming it is the whole answer. Any sort (heap sort, and others that arrive with the next design strategy) works; the specific sort is not fixed, but its cost is what the total answer depends on.

Exam note: when asked for the time complexity of fractional knapsack, the answer is , and the reason is the sort. Naming the sort is the whole answer. A bare "" with no mention of the sorting step earns less credit — the explanation is the point.

8.5.7 Student Questions and Answers

Q: Why did we sort the objects by value? Value is profit by weight — what is the per-unit profit of each object? A: Exactly. Value is the profit per unit weight — per-unit profit gives a clear understanding of how much profit we can get by taking an object completely or by taking a fraction. Only because we sorted by value could we apply the method this easily: we are sure that taking all of object 3 is much more beneficial than taking one-fourth of object 1. Without the value computation we could not make that decision.

During the table fill, a student doubted whether object 2 could be taken whole:

Q: Can we take object 2 completely? Its weight is 25 and the remaining capacity is 30 — but I thought we could not. A: Yes, we can. You confused profit with weight. The check is weight against remaining capacity: 25 is less than 30, so the whole object goes in. The profit of 40 is only used in the profit column, not in the fit test.

Another student asked about the supply of each object:

Q: Do we have only one unit of each object? A: Yes — in this problem we have only one unit of each object. Consider it a real-world case: there is a single gold block of each size. If more units were available, we could keep increasing the profit by taking more units.

And one more, linking back to the coin problem:

Q: Can we think of the coin problem as having an infinite number of coins of each denomination? A: Yes, you can think of it that way too — as if there is no limit on the count of coins of each denomination. The greedy reasoning is unchanged.

Real-world: fractional knapsack is exactly the model behind cutting stock, portfolio optimization, and download managers — anywhere a divisible resource is packed into a limited container to maximize value. The 0/1 knapsack variant (indivisible objects) comes later under a different technique.

Recap and bridge: the fractional knapsack is solved by taking the highest value-per-weight object next — sort by , fill whole objects while they fit, then finish with a fraction of the next object, all in . The ship loading problem in the next section is the same machinery with a different objective: count, not profit.

8.6 Ship Loading Problem

8.6.1 Problem Statement

A second optimization problem in the same family: a ship is to be loaded with containers. The aim is to load the ship with the maximum number of containers. Each container has a weight , and the ship has capacity . The variable denotes whether container is loaded: if the container is not loaded, if it is.

The constraint is the same shape as knapsack:

where is the capacity of the ship, and the optimization is to maximize the number of containers loaded.

Ship loading (the problem): containers with weights are loaded onto a ship of capacity . The variable says whether container is loaded; the total weight must stay at or below ; the objective is to maximize — the number of containers on board. The only difference from the knapsack is the objective: knapsack maximizes profit, ship loading maximizes count.

Since the 0/1 knapsack has not been studied yet, treat this as a fractional knapsack problem with the value of restricted to either 0 or 1. When 0/1 knapsack is covered, the instructor said, this problem will be revisited from a different angle.

8.6.2 Greedy Strategy

The greedy algorithm loads the ship in stages — one container per stage — and at each stage selects the container with the least weight. Lightest first maximizes the count of containers, which is the objective here (different from fractional knapsack, where highest value first maximizes profit).

Worked example — container loading. Eight containers with weights 100, 200, 50, 90, 150, 50, 20, 80 (in weight units) and ship capacity . The greedy criterion is lightest first, so sort the weights: 20, 50, 50, 80, 90, 100, 150, 200.

Container (original no.) Weight Load? Remaining capacity
7 20 yes 400 − 20 = 380
3 50 yes 380 − 50 = 330
6 50 yes 330 − 50 = 280
8 80 yes 280 − 80 = 200
4 90 yes 200 − 90 = 110
1 100 yes 110 − 100 = 10
5 150 no — 150 > 10 10
2 200 no — 200 > 10 10

Loaded containers: 7, 3, 6, 8, 4, 1 — six containers with total weight 390, leaving 10 units unused. Sense-check: the next lightest container weighs 150, more than the 10 units left, so nothing else fits; and any selection of seven containers weighs at least the seven lightest, , which cannot fit — so six is the maximum.

The greedy algorithm itself is cheap to run: sorting the containers by weight costs , and the loading pass visits each container once, so the whole procedure is . What earns the answer credit is the same habit as everywhere in this unit: state the objective, state the greedy criterion (lightest first), and justify why the choice is safe.

Q: By looking at a problem, will we be able to tell whether the greedy method can be applied? A: At least this much you can check: the problem will be an optimization problem — a maximization or minimization. That much confidence is a good enough starting point. Then compare it with the known greedy problems and prove the greedy choice property for your case.

Exam note: the instructor flagged this as a sample of the first type of greedy exam problem — maximization or minimization problems like the fractional knapsack. The second type is task scheduling, next. When you meet a new problem in the exam, the first two questions to ask are: is it an optimization problem, and does it resemble a known greedy problem?

8.7 Job Sequencing with Deadlines

Task scheduling is the second category of greedy problems. Two versions appear in the literature; both are discussed — job sequencing with deadlines first, then interval scheduling (next session).

8.7.1 Problem Statement

Given a set of jobs, where each job has an integer deadline and a profit , find the set of jobs such that all jobs are completed within their deadlines and the profit earned is maximum.

Three constraints define the setting:

  1. Only one machine is available for processing the jobs.
  2. Only one job can be processed at any point of time.
  3. A job is complete when it is processed on the machine for one unit time — every job takes exactly one unit, which is why durations are not mentioned in the data; only deadlines are.

The problem: find the order in which to sequence the jobs so that every scheduled job finishes within its deadline and total profit is maximized. Note that we do not have to schedule all the jobs — the subset that fits the deadlines and maximizes profit is the answer.

Job sequencing with deadlines (the problem): jobs, job with integer deadline and profit . One machine, one job at a time, each job takes exactly one unit of time. Pick the subset of jobs and an order to run them so that every picked job finishes by its deadline and the sum of profits is as large as possible. The answer is a subset, not a full schedule — jobs that cannot fit inside their deadlines are simply left out.

8.7.2 The Clock Representation

The instructor's device for solving by hand: draw a clock. Find the maximum deadline in the table — that decides how many slots the clock has. If the maximum deadline is 3, divide the circle into 3 equal slots and think of the time running from 12 noon to 3 pm, with each job needing one hour (one unit of time). A job cannot be paused in the middle.

The rule: for each job, allot the last possible slot before its deadline — never the first available one. A job with deadline 2 could finish by 1 o'clock, but put it in the 1-to-2 slot anyway. The reason appears immediately in the example: an earlier slot may be needed by a job with a tighter deadline, a job that can only go there.

Intuition — the clock is a timeline. Picture a clock face with only the hours that matter: for maximum deadline 3, the circle is cut into three one-hour slices — 12 to 1, 1 to 2, 2 to 3 — and time runs from 12 noon to 3 pm. A job with deadline 3 may end at or before 3 o'clock, so it can occupy any of the three slices; a job with deadline 1 must be done by 1 o'clock, so it can occupy only the first slice. The slice boundaries are the deadlines of the jobs — that is why the maximum deadline decides how many slices exist.

A note of caution the instructor added: the "clock" is not literally a clock — it is a data structure (a slot list); the clock is only an easy picture for understanding.

Warning — the clock is a picture, not the machinery. The clock is a data structure — a list of slots — drawn as a circle only for ease of understanding. The slot list is an array indexed by time position: index holds the job scheduled in the -th unit of time. Do not carry "noon to 3 pm" into the algorithm; carry the idea — slots numbered 1 to , each holding one job.

8.7.3 Worked Example 1

Five jobs:

Job Profit Deadline
1 20 2
2 10 1
3 15 2
4 1 3
5 5 3

Read the deadlines as times: job 1 must finish before 2 o'clock, job 2 before 1 o'clock, jobs 4 and 5 before 3 o'clock.

Step 1 — arrange in decreasing order of profit: job 1 (profit 20, deadline 2), job 3 (15, deadline 2), job 2 (10, deadline 1), job 5 (5, deadline 3), job 4 (1, deadline 3). The greedy choice mirrors the knapsack ordering — there we sorted by value (profit per unit weight); here we sort by profit and pick the highest-profit job first.

Step 2 — the clock. Maximum deadline is 3, so the clock has 3 slots: 0–1, 1–2, 2–3.

  • Job 1 (profit 20, deadline 2): allot the last possible slot before 2 — slot 1–2. Profit: 20.
  • Job 3 (profit 15, deadline 2): slot 1–2 is taken, so step back to slot 0–1, which is empty. Profit: 15.
  • Job 2 (profit 10, deadline 1): only slot 0–1 exists before 1 o'clock and it is occupied. This job cannot be scheduled.
  • Job 5 (profit 5, deadline 3): the last slot before 3 is 2–3, empty. Profit: 5.
  • Job 4 (profit 1, deadline 3): no empty slot remains before 3. Cannot be scheduled.

Final answer. Total profit:

Scheduled jobs: job 1, job 3, and job 5 — total profit 40. The clock ends with slot 0–1 = job 3, slot 1–2 = job 1, slot 2–3 = job 5, and no slot left over. Sense-check: the only unscheduled jobs are 2 (profit 10) and 4 (profit 1). Job 2's deadline 1 leaves it exactly one possible slot — 0–1 — which job 3 occupies, so it cannot be added; job 4 would add only 1. No feasible plan can beat 40.

The numbering matters: the instructor pointed out that depending on how you number the rows you must state exactly which numbers you mean; here the original job numbers 1, 3, 5 are the ones picked.

8.7.4 Student Questions and Answers

Q: Why did we put job 1 in the 1-to-2 slot instead of the 0-to-1 slot? A: Because some other job may mandatorily need the first slot. Suppose the 0-to-1 slot had been taken by job 1 — a job with deadline 1 (like job 2 here) can only go in that slot. Putting job 1 in its last possible slot leaves the earlier slot free for jobs with tighter deadlines. That is why the rule is: allot the last possible slot, not the first.

A hypothetical variant came up next — what if a higher-profit job existed:

Q: If there had been a job with profit 40 and deadline 2, would we pick it? A: Yes, definitely. When we arrange in decreasing order of profit, that job comes first and is picked; the profit-15 job would drop out of the final solution. The 40-profit job would take the slot the 15-profit job had.

The time unit itself was questioned too:

Q: The duration of jobs is not mentioned. Can we take the time unit as 30 minutes instead of an hour? A: Feel free to use any unit — 30 minutes, 5 minutes, anything. What matters is the number of slots: with maximum deadline 3 there are only 3 slots regardless of the unit. One unit of time is one slot, whatever the unit is.

And whether every task must be processed at all:

Q: Do we have to process all the tasks? A: No. We pick only those jobs that can be executed within their deadlines and still maximize profit. We may not be able to execute all of them; sometimes we can, but we do not know in advance. The algorithm finds the subset.

8.7.5 The Algorithm

If the clock picture is clear, the algorithm is easy — the "clock" is a list (slot array) and the algorithm is exactly what we did by hand.

1.  Arrange the jobs in decreasing order of profit
2.  Initialize the list (the "clock") with zeros: list[1..d_max] = 0
3.  P = 0                                        // total profit starts at zero
4.  for i = 1 to n:
5.      k = d_i                                  // start from the job's deadline position
6.      while k > 0:
7.          if list[k] == 0:                     // this slot is empty
8.              list[k] = i                      // place the job in this slot
9.              P = P + p_i                      // add the profit
10.             break                            // job is placed; move to the next job
11.         k = k - 1                            // slot taken; try the earlier slot

Trace the second sorted job (profit 15, deadline 2) through the loop: starts at 2, but list[2] is occupied by the first job, so the loop does not place it — it decrements to 1, finds list[1] empty, and places the job there. Decrementing continues down to 0 if needed; if no slot opens up, the job is simply not scheduled. The list is our clock: the deadline position indexes the slot, and an empty slot means the position is free.

Inputs and outputs of the algorithm. Input: jobs, each with deadline and profit , and — the largest deadline in the data. Output: the schedule stored in the list (the slot array) and the total profit . The list has entries, one per time unit, all zero at the start; a zero entry means the slot is free, and placing job in slot records there. The while loop implements the last-slot rule: start at the job's deadline and walk backward through the slots until a free one appears.

8.7.6 Time Complexity

The time complexity is , and this one needs care. The sorting suggests — and many students answer exactly that — but sorting is not the dominant term here. The outer loop runs times, and the inner while loop (over ) can also run up to steps in the worst case: if all jobs have the same (large) deadline, the loop keeps decrementing through occupied slots. One loop inside the other — the answer is n squared — gives

The instructor's rule for this course: a time complexity answer without an explanation gets zero credit. The reason here is the inner loop — in extreme situations it can go all the way to , so the two loops nest into . is the complexity of the sort alone, and that is not the whole algorithm.

Pitfall — answering because of the sort. Sorting is , but the whole algorithm is . The outer loop visits jobs, and for each job the inner while loop can walk through up to slots before finding an empty one — worst case when all jobs share one large deadline and the slots fill up. A job with deadline can force to decrement almost to zero. One loop inside the other is , so the answer is .

Exam note: expect to explain why the complexity is — the sort alone would be , but the nested loop dominates. A bare answer without reasoning earns nothing; the instructor's rule for this course is that a time complexity answer without an explanation gets zero credit.

8.8 Exam-Style Problem: Maximizing Bonus Marks

The instructor walked through an exam question from the same family, to show the pattern — and to show how wordy exam statements reduce to one simple demand.

8.8.1 The Question

A set of problems is given; each problem carries 1 mark, plus a bonus if it is submitted within a specified number of days (its deadline). The objective stated in the question is to maximize the bonus marks — the number of problems solved is not the objective.

The reduction trick — long statements, short demand. A wall of paragraphs can conclude in one line or half a line of actual demand. The instructor's habit for the exam: read fully, then reduce. This question reduces to "arrange the table in the descending order of bonus" — that is the entire task. Do not panic because there are many sentences; the extra words are the trap, not the task.

Reducing the question: "arrange the table in the descending order of bonus." That is the entire task in one line. The instructor's advice for the exam: long paragraphs of question text conclude in maybe one line or half a line of actual demand — do not panic because there are many sentences; reduce and go. A similar practice variant shown alongside had nine jobs and a maximum deadline of seven, needing seven slots.

The exam data (as presented in class): the maximum deadline is 6, so the clock has 6 slots — 1 through 6. Each attempted problem earns its 1 mark plus its bonus when it is submitted within its deadline.

Exam note: wordy exam statements reduce to one line; arrange the table in descending order of bonus. Extra sentences are how the paper is made to look hard — the demand inside is usually a single familiar operation.

8.8.2 Walkthrough

Arrange the problems in decreasing order of bonus, then place them one by one in their last possible slot.

The problems, sorted by decreasing bonus:

Problem Bonus Deadline
2 7 1
6 5 2
3 2 3
7 1 6

(The remaining problems 1, 4, and 5 have smaller bonuses; in the walkthrough they are never attempted, so their values do not affect the answer. The schedule follows the instructor's walkthrough exactly.)

The clock has 6 slots, one per day: slot 1 (day 0–1), slot 2 (1–2), slot 3 (2–3), slot 4 (3–4), slot 5 (4–5), slot 6 (5–6).

  • Problem 2 — bonus 7, deadline 1: first in sorted order, the maximum bonus. Slot 1 (0–1). Marks earned: 1 + 7 = 8.
  • Problem 1 — deadline 1: slot 1 is already taken by problem 2 (the maximum-bonus problem); cannot be attempted.
  • Problem 6 — bonus 5, deadline 2: last slot before 2 is slot 2 (1–2), empty. Marks: 1 + 5 = 6. Running total: 8 + 6 = 14.
  • Problem 5 — deadline 2: no empty slot within the first two days (both slots 1 and 2 are occupied, and each problem needs one full day); cannot be attempted.
  • Problem 3 — bonus 2, deadline 3: slot 3 (2–3), empty. Marks: 1 + 2 = 3. Running total: 17.
  • Problem 4 — deadline 3: no empty slot before 3; cut.
  • Problem 7 — bonus 1, deadline 6: slots 4–5 and 5–6 are empty; per the algorithm, allot the last possible slot before the deadline — slot 6 (5–6). Marks: 1 + 1 = 2. Running total: 19.

Final answer. Attempted problems: 2, 6, 3, and 7. Total marks: 8 + 6 + 3 + 2 = 19. Total bonus: 7 + 5 + 2 + 1 = 15.

Sense-check: the bonus total 15 is the maximum possible — 7 + 5 + 2 + 1 are the four largest bonuses whose deadlines allow a schedule. Problem 2 owns day 1, so nothing else with deadline 1 fits; problems 6 and 3 take days 2 and 3; problem 7 parks in its last allowed slot and still earns its bonus. Slots 4 and 5 stay empty because no remaining problem has a deadline beyond 3 except problem 7, which the algorithm places in its last allowed slot.

There is no limit on the number of problems — the question asked for maximum bonus, not for solving fewer problems, so extra problems without bonus are harmless. The instructor noted that you could even attempt all the problems and simply collect bonus only where the timing allows.

8.8.3 The Mistake and the Correction

During the walkthrough the instructor initially skipped problem 7, saying "you will not get any bonus" for it. A student spotted the problem.

Q: With problem 7, bonus is coming — the total can go up to 15. Why did we stop at 14? A: Let me re-check. In my reference the value was written as 2, which is why I skipped it — my mistake. If the bonus is 1, please go for problem 7 as well; the total bonus reaches 15.

The instructor acknowledged the error openly ("my bad, that was my mistake") and included problem 7. Two lessons for students: the last-slot rule is applied even when earlier slots are free (deadline 6 → slot 6, per the algorithm), and errors like this are exactly why the walkthrough should be checked against the table.

Pitfall — trusting a walkthrough without re-checking. The reference value for problem 7 was misread as 2, and the instructor skipped it on that basis. The student's question — "why did we stop at 14 when 15 is reachable?" — forced the re-check that caught the error. The lesson generalizes: after solving, verify that no un-picked job still fits and would raise the objective. The check against the table is what turns a plausible answer into a correct one.

8.8.4 Student Questions

Q: In this problem, the total marks will be 19, but the total bonus marks will be 15. Which one does the question ask about? A: It depends on whether the question is about total marks or total bonus marks. That tells you how you may limit the number of questions — the objective of the optimization changes which problems you select.

The two numbers answer two different questions. Total marks (19) counts every attempted problem's base mark plus its bonus; total bonus (15) counts only the bonus parts. If the question asked for maximum total marks, you would attempt more problems even when they carry no bonus (up to all of them, since slots remain free); if it asks for maximum bonus, you stop once no bonus remains obtainable. Reading which quantity the question names is the first step.

Exam note: this is the second type of greedy exam problem — task scheduling. The job sequencing variant is done; interval scheduling is the second version, next session. Exam problems from greedy method and task scheduling were to be posted on the course forum as discussion topics for practice — the nine-job, maximum-deadline-seven variant is a good self-test.

8.9 Applications of the Greedy Method

8.9.1 Classic Applications from the Textbook

The textbook lists a family of problems where greedy is a standard, successful approach:

  • Portfolio optimization — selecting the best portfolio by some objective (covered in 8.4).
  • Cutting stock problem — cutting standard stock into specified sizes while minimizing waste (covered in 8.4).
  • Huffman encoding for text compression — a classic greedy algorithm; the textbook covers it and it is worth reading through. The greedy step is memorable: repeatedly combine the two least-frequent trees, a "merge the cheapest pair" rule that builds an optimal prefix code.
  • Web auction optimization — explained in detail later in the textbook; reading it through is expected.
  • k-means procedure in clustering — if you have seen data mining or machine learning, you know k-means uses the sum of squared distances: examples with the minimum sum of squared distances to a cluster center are grouped in one cluster, and larger distances push examples into different clusters. Conceptually, partitioning examples into clusters so as to minimize the sum of intra-cluster quantities and maximize the sum of inter-cluster quantities is an optimization problem — and it can be viewed as an application of the greedy idea.

The general pattern the instructor repeated: wherever maximize or minimize appears, an optimization problem is present, and greedy should be the first strategy considered — at least as a starting point.

The one-line pattern for the whole session: every greedy problem is an optimization problem — configurations, an objective function, and a sequence of feasible, locally optimal, irrevocable choices. When you meet a new problem, ask whether maximize or minimize appears, compare the problem with the known greedy families, and prove the greedy choice property for your case before trusting the answer.

Real-world: portfolio optimization (finance), cutting stock (paper and metal industries), download managers (networking), Huffman encoding (compression in ZIP, image formats), web auctions (e-commerce), and k-means (customer segmentation, image compression, recommendation systems).

Next session: interval scheduling — the second task-scheduling problem — and the remaining algorithm design techniques.

Exam Guidance Summary

Mid-semester feedback (heap sort question). The heap sort question from the regular exam is still being evaluated for some students, and many of you got zero on it.

Q: For the heap sort question I used a max heap. Why zero? A: The expected answer used a min heap. Read the question again: it asked for in-place sorting. With a min heap you sort ascending directly, in place. With a max heap you get ascending order and then need one more step to reverse it — and the word "in place" is what makes that extra step wrong for the question. The word "in place" was the only catch in that question. If the question had been a plain "heap sort," everyone would have done it; the in-place requirement is what demanded a bit of thought. Max-heap answers get less credit, for sure — and if you have a complete, correct max-heap answer that scored zero, apply for REWAL when the window opens; answer keys will be uploaded.

Evaluation rules. Papers are evaluated by a team to ensure uniformity — the same question is graded by the same person for all students, and the most effective answer fetches the maximum credit; correct-but-less-effective answers get relatively less. All papers are reviewed by the instructor. The heap question that is still pending is being resolved.

Paper design. The regular paper felt very lengthy — that was deliberate. In an online exam, the paper is either made 90% tough or a bit lengthy; those are the only two tactics, so that you are challenged or run out of time to look elsewhere. You can write what you know.

Regular vs makeup. The makeup paper felt easier than the regular one, but the reason is pattern familiarity: after the regular paper you know what to expect. If the makeup had come first, it would have felt the same.

Difficulty and grading. The mid-semester was consciously made a bit tough so that you understand the complexity of the course. With a similar paper now, you would score much better — you know the question types and timing. The first time is always a shock. Grading is relative, and everyone is on the same page, so this helps all of you.

Final exam. The final exam is the full syllabus, with a marks split of 25/75 (as announced at the end of the session).

Time complexity answers. A time complexity answer without an explanation gets zero credit — for job sequencing with deadlines, explain the inner loop; for fractional knapsack, name the sorting step.

Reading long questions. Long exam statements are how you are tricked — extra words are added to an otherwise simple question ("instead of asking what data structure can be used, I will put some extra words and all of you panic"). Read fully and reduce: many paragraphs conclude in one line, like "arrange in descending order of bonus."

Problem-solving study advice. Problem solving is a gap: concepts are explained in class, but we do not get to learn through problem solving. The plan: one or two problems (maximum three) solved in class; the remaining ones posted as discussion topics on the course forum, where you discuss and solve together, with the instructor joining in when needed. You should also try to solve as many online and textbook questions as possible. The exam problems from greedy method and task scheduling are being uploaded for practice; a nine-job, maximum-deadline-seven variant is a good self-test.

Assignment 1 (greedy part). The second part of the assignment is a greedy design — that is the highlight; you may use any data structure you want, including a heap or a set (set is allowed because it was not explicitly covered in class) and Python's built-in ADTs. The design document must explain which data structure you used, the algorithm, and the time complexity. The input file format will be exactly the same as the example file — same labels, different values — and boundary conditions will be tested, so follow best coding practices: exit gracefully, with a message explaining the reason. The intention of the first part of the assignment is for you to implement the ADT yourself rather than only use a library implementation; you may use libraries if you cannot implement it yourself, but implementing it yourself is the point.

Key Industry Applications

  • Bank cashier change-making — the coin problem that opened the session is a daily routine in retail; greedy works when the coin system has the greedy choice property (as with 25, 10, 5, 1). Vending machines and point-of-sale terminals run the same "largest coin first" rule every time they give change.
  • Portfolio optimization — selecting the best portfolio (distribution of investment across sectors) to maximize expected returns while minimizing financial risk.
  • Cutting stock problem — hardware factories cut standard-size stock material (paper rolls, sheet metal) into specified sizes while minimizing material waste.
  • Internet download managers — data is broken into chunks and the server greedily packs chunks to fill the maximum size retrievable in one go.
  • Huffman encoding — greedy algorithm for text compression, used in ZIP files and image formats; it repeatedly merges the two least-frequent symbols, packing more frequent symbols into shorter codes.
  • Web auction optimization — greedy ideas behind auction mechanics, covered in detail later in the textbook.
  • k-means clustering — partition examples into clusters minimizing intra-cluster (sum of squared distances) and maximizing inter-cluster separation; used in customer segmentation, image compression, and recommendation systems.
  • Vacation backpack packing and night-before-exam study planning — the everyday greedy applications the class itself came up with: pack the highest value-per-weight item first, and study the highest-yield topic first.

DSA Lecture 8 notes · Greedy Method

Data Structures and Algorithms· postgraduate· 2026-08-09

Sections Breakdown

18.1 Algorithm Design Techniques — the Course Pivot

The pivot from data structures to algorithm design techniques, the definition of a design technique, and the carpentry hand-tool analogy.

28.2 The Change-Making Problem — Greedy Thinking by Example

The coin problem introduces greedy thinking: change for 32 paise succeeds, change for 20 paise with coins 15, 10, 1 shows greedy failing.

38.3 Greedy Method — Definition and Properties

Configurations and objective functions, the greedy choice property, optimal substructure, and the three properties of every greedy choice.

48.4 Greedy Method in Real Life

Everyday greedy applications: exam-night study planning, backpack packing, portfolio optimization, cutting stock, and download managers.

58.5 Fractional Knapsack

The fractional knapsack problem and its formulation, value per unit weight, the three-gold-blocks worked example (profit 82.5), the algorithm, and O(n log n) complexity.

68.6 Ship Loading Problem

Loading the maximum number of containers with the lightest-first greedy choice, an eight-container worked example, and complexity.

78.7 Job Sequencing with Deadlines

One machine, one job per unit of time: sort by profit, allot the last possible slot on the clock, with a worked example (profit 40) and O(n^2) complexity.

88.8 Exam-Style Problem: Maximizing Bonus Marks

An exam-style scheduling walkthrough: arrange by descending bonus and place each problem in its last possible slot; the instructor's misread of problem 7 is corrected in class.

98.9 Applications of the Greedy Method

The textbook's greedy applications: Huffman encoding, web auction optimization, k-means clustering, and the maximize-or-minimize pattern.

10Exam Guidance Summary

Exam guidance from the session: the heap sort min-heap question, evaluation rules, paper design, the 25/75 final split, and time-complexity answer expectations.

11Key Industry Applications

Where greedy thinking works in industry: change-making, portfolio optimization, cutting stock, download managers, Huffman encoding, web auctions, and k-means.

Postgraduate students studying algorithm design techniques

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Algorithm Design Techniques — the Course Pivot

Must-know: An algorithm design technique is a general approach to design algorithms, not one specific algorithm and not about time complexity.

Top pitfall: Answering that a design technique means 'optimized and giving minimum time complexity' — it has nothing in particular to do with time complexity.

Self-check: In the carpentry analogy, what does the specialized power tool stand for?

Connects to: 8.2

The Change-Making Problem — Greedy Thinking by Example

Must-know: Greedy thinking always gives a solution but only gives the optimal solution when the problem has the greedy choice property.

Top pitfall: Assuming greedy is always optimal; the 20-paise example (15/10/1 coins) is the counterexample.

Self-check: Why does greedy fail on change for 20 paise with coins 15, 10, 1?

Connects to: 8.3, 8.3.2

Greedy Method — Definition and Properties

Must-know: A greedy choice must be feasible, locally optimal, and irrevocable; the problem must have the greedy choice property for the answer to be optimal.

Top pitfall: Believing greedy is always optimal; coin set {30, 25, 1} fails for change 40 (greedy 30+5+5 = 3 coins vs optimal 20+20 = 2 coins).

Self-check: What are the three properties every greedy choice must satisfy?

Connects to: 8.2, 8.5, 8.7

Greedy Method in Real Life

Must-know: Any problem with a maximize or minimize objective is an optimization problem, and greedy should be the first option considered.

Top pitfall: Treating greedy as guaranteed optimal in real-life settings — it is a starting point and a natural candidate, not a guarantee.

Self-check: Give one real-life situation where the greedy strategy applies, and name its objective function.

Connects to: 8.5, 8.9

Fractional Knapsack

Must-know: Fractional knapsack is solved by sorting objects by value v_i = p_i/w_i and taking the highest-value next; time complexity is O(n log n) because of the sorting step.

Top pitfall: Confusing profit with weight when checking whether an object fits — the fit test compares weight against remaining capacity only; and quoting O(n) while forgetting the sort.

Self-check: With M = 40 and objects (20,30), (25,40), (10,35), why is the fraction of object 1 taken equal to 0.25?

Connects to: 8.3, 8.6, 8.7

Ship Loading Problem

Must-know: Ship loading maximizes the number of containers; greedy picks the lightest container at each stage, and this is the first type of greedy exam problem (maximization/minimization).

Top pitfall: Using highest value first (as in knapsack) when the objective is count — lightest first is the greedy criterion here.

Self-check: What greedy criterion does ship loading use, and what does it maximize?

Connects to: 8.5, 8.7

Job Sequencing with Deadlines

Must-know: Sort jobs by decreasing profit and allot each the last possible slot before its deadline; time complexity is O(n^2) because the inner k loop can run up to n — a bare answer without the explanation gets zero credit.

Top pitfall: Answering n log n because of the sort — the nested k loop dominates and the answer is n squared; and allotting the first free slot instead of the last possible one.

Self-check: Why is job 1 with deadline 2 placed in the 1-to-2 slot rather than the 0-to-1 slot?

Connects to: 8.3, 8.5, 8.8

Exam-Style Problem: Maximizing Bonus Marks

Must-know: Wordy exam statements reduce to one line — arrange the table in descending order of bonus and allot the last possible slot; know whether the question asks for total marks or total bonus, since the objective changes the selection.

Top pitfall: Skipping a job that still fits because its reference value was misread — re-check the table and verify no un-picked job would raise the objective.

Self-check: Why is problem 7 placed in slot 6 even though slots 4 and 5 are empty?

Connects to: 8.7, 8.3

Applications of the Greedy Method

Must-know: Greedy is the first strategy to consider for any optimization problem; classic applications include Huffman encoding, web auctions, and k-means clustering.

Top pitfall: Forgetting that the greedy idea is only a starting point — the greedy choice property must still be established for each problem.

Self-check: Name three textbook applications of the greedy method.

Connects to: 8.4, 8.5

Exam Guidance Summary

Must-know: The heap sort exam question expected a min heap because it asked for in-place sorting; a time complexity answer without explanation gets zero credit.

Top pitfall: Using a max heap for an in-place heap sort — you get ascending order and then need one more step to reverse it.

Self-check: Why was a min heap the expected answer for the heap sort question?

Connects to: 8.7, 8.5

Key Industry Applications

Must-know: Greedy thinking shows up in change-making, portfolio optimization, cutting stock, download managers, Huffman encoding, web auctions, and k-means clustering.

Self-check: Which greedy application is used in ZIP file compression?

Connects to: 8.4, 8.9

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.