Greedy algorithms basics
Computer Science · Algorithms
Question 1 of 10
0The weight of a minimum spanning tree is:
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Greedy algorithms basics explained
A greedy algorithm builds a solution one step at a time, always choosing the option that looks best at that moment and never reconsidering the choice. It is fast and simple, but it gives the best overall answer only for some problems.
Greedy methods are correct when the problem has the greedy-choice property: a locally best choice can always be extended into a globally best solution. Proving this is the main work in a greedy algorithm, and many problems do not have the property.
Greedy methods succeed on minimum spanning trees and Huffman coding. A common greedy scheduling strategy is earliest finish time. Greedy methods fail on many other problems, which is why dynamic programming, which compares options, is needed for some tasks.
Worked example
Activities are given as (start, finish) times: A (1, 4), B (3, 5), C (0, 6), D (5, 7), E (8, 9) and F (5, 9). Choose the largest set of activities that do not overlap.
- Sort by finish time: A (4), B (5), C (6), D (7), E (9), F (9).
- Pick A, which finishes at 4. Skip B and C, which start before 4.
- Pick D, which starts at .
- Pick E, which starts at . Skip F, which starts at 5 before E finishes at 9.
The greedy choice gives A, D and E, so 3 activities fit.
What you will practise
104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Greedy algorithms:
- Greedy works when local choices lead to:
- Making change with coins often uses a:
- Greedy algorithms do not always find:
- Activity selection is classic for:
- A greedy algorithm makes each decision by:
- Huffman coding builds a prefix code by repeatedly:
- In a greedy algorithm, a decision once made is:
…and 96 more.