Module 10 · Dynamic Programming and Greedy · Lesson 36 of 40
Greedy algorithms: the best choice right now
Make the choice that looks best at each step and never look back. When it works, and when it fails.
In this lesson · about 24 minutes
- Explain the greedy idea and how it differs from DP
- Solve interval scheduling and jump game greedily
- Show a case where greedy gives the wrong answer
A greedy algorithm makes the choice that looks best right now, then moves on and never changes its mind. It is simple and fast, often just a sort plus one loop: O(n log n).
Greedy vs DP
DP considers all choices and keeps the best. Greedy commits to one choice per step. Greedy is only correct when you can prove that the local best choice never ruins the final answer (the greedy choice property).
Classic 1: activity selection
Many meetings want one room. Fit in as many as possible. The greedy rule that works: always pick the meeting that ends earliest, then skip any that overlap with it. Ending early leaves the most room for the rest.
meetings.sort(key=lambda m: m[1]) # by end time
count, last_end = 0, float("-inf")
for start, end in meetings:
if start >= last_end:
count += 1
last_end = end
Classic 2: jump game
Each number says how far you may jump from that spot. Can you reach the end? Walk left to right, keeping the farthest index you could reach so far. If you ever stand beyond it, you're stuck.
Classic 3: fractional knapsack
If you may take part of an item (like flour or gold dust), take items with the best value per kilo first. Greedy is perfect here. But for the 0/1 knapsack (whole items only), greedy can fail, and you need DP.
When greedy fails
Coins worth 1, 3 and 4. Make 6. Greedy takes the biggest coin first: 4 + 1 + 1 = three coins. The best is 3 + 3 = two coins. With these coins, use DP (the coin-change table from the last lesson).
Other greedy classics: minimum meeting rooms (with a heap), Huffman coding, Kruskal and Prim (Module 9), gas station, assigning cookies to children.
Try it: greedy coins can fail
Exercise
Most meetings in one room
Each meeting is (start, end). A meeting can start exactly when another ends. Write max_meetings(meetings) that returns the largest number that fit in one room, using the "earliest end first" greedy rule.
Exercise
Jump game
jumps[i] is the farthest you may jump forward from index i. Starting at index 0, can you reach the last index? Write can_reach_end(jumps) by keeping the farthest reachable index.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.