Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

Greedy Algorithms: The Best-Looking Choice, Right Now

Kate owes Tom 28 cents from a till of 10, 5, 2 and 1. Like any cashier she grabs the biggest coin that fits, again and again: that's a greedy algorithm. Fast and right for normal coins, but with coins of 4, 3 and 1 it hands out three coins where two would do.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

What you will learn

  • Explain the greedy rule: take the best-looking choice now and never go back
  • Write a greedy coin-change function and trace it by hand
  • Show with the 4, 3, 1 coins why greedy can miss the best answer
  • Know when greedy is safe and name problems where it is proven to work

Before you start

  • Python loops and lists
  • Big-O notation

Kate works at a cafe till. Tom buys a juice for 72 cents and pays with 100, so Kate owes him 28 cents. The till has coins of 10, 5, 2 and 1. Which coins make 28 cents with as few coins as possible? And Kate wants it fast; there's no time to try every mix. The answer: 10, 10, 5, 2 and 1. Five coins.

Grab the biggest coin that fits

What does any cashier do? She grabs the biggest coin that fits. Ten. Then ten again. Now 8 is left. Ten doesn't fit into 8 any more, so she moves to the next coin, five. Now 3 is left. Then two, then one, and nothing is left. Five coins in Tom's hand.

That's the greedy rule: take the best-looking choice right now, and never go back to change it. One quick choice at a time, with no looking back.

Greedy change in Python

def give_change(amount, coins):
    change = []                       # coins we hand out
    for coin in coins:                # biggest coin first
        while amount >= coin:         # does it still fit?
            change.append(coin)       # take it
            amount -= coin
    return change

The loop goes over the coin sizes, biggest first. While the coin still fits, take it and reduce what's left. The function never goes back to change a choice.

from greedy import give_change

coins = [10, 5, 2, 1]          # biggest first
amount = 28                    # Tom's change

change = give_change(amount, coins)
print("Change for " + str(amount) + ": " + str(change))
print("Coins used: " + str(len(change)))
Change for 28: [10, 10, 5, 2, 1]
Coins used: 5

The coins must be listed biggest first. That order is what makes it greedy.

Step by step

Left to giveCoin triedFits?Action
2810yestake, 18 left
1810yestake, 8 left
810nomove on
85yestake, 3 left
35nomove on
32yestake, 1 left
12nomove on
11yestake, 0 left, done

Each coin size is looked at once, and no choice is ever changed.

A full till

from greedy import give_change

till = [200, 100, 50, 20, 10, 5, 2, 1]  # 8 coin sizes
amounts = [28, 999, 99_999]
for amount in amounts:
    used = len(give_change(amount, till))
    print(f"{amount:6,d} cents: {used} coins")
    28 cents: 4 coins
   999 cents: 11 coins
99,999 cents: 506 coins

99,999 cents in 506 coins, picked in one pass. That's about a hundred times more money than 999 cents, but only 46 times more coins, because 499 of those coins are the biggest coin, the 200. The loop hands out one coin per round and never tries another mix, which is why greedy is so fast.

Breaking it: a strange set of coins

from greedy import give_change

coins = [4, 3, 1]          # a strange set of coins
amount = 6

change = give_change(amount, coins)
print("Change for " + str(amount) + ": " + str(change))
print("Coins used: " + str(len(change)))
Change for 6: [4, 1, 1]
Coins used: 3
Making 6 cents from coins 4, 3 and 1. Greedy takes 4 first, then 1 and 1: three coins. The best answer is 3 and 3: two coins. greedy 4 1 1 = 6, three coins best 3 3 = 6, two coins The 4 looked best, but it left a 2 that only 1s can fill.
Greedy can't undo a choice, so it never tries 3 + 3.

Greedy grabs 4 first because it's the biggest coin that fits. Then only 2 is left: 4 doesn't fit, 3 doesn't fit, so it takes 1 and 1. Three coins. But 3 plus 3 is also 6, with two coins. Greedy never tried it, because it had already taken the 4 and can't undo a choice. The best-looking choice right now is not always the best in the end.

When can you trust greedy?

With 10, 5, 2 and 1, take the 10: you could swap it for 5 and 5, but that's two coins instead of one. Any swap uses the same number of coins or more, so grabbing the biggest first can never hurt. The lesson also checked every amount up to 300, and greedy always gave the fewest coins. With 4, 3 and 1, the big coin is a trap. So before you trust greedy, ask one question: could a smaller first choice ever win? When it can, you need a method that compares choices, such as dynamic programming.

What it costs

c is the number of coins handed out.

TillSpeedFewest coins?
10, 5, 2, 1O(c), one round per coin plus one check per coin sizeyes
Full till, 200 down to 1O(c)yes
4, 3, 1O(c)no, not always

Where you meet greedy

  • Making files smaller: zip-style codes join the two rarest letters first, again and again.
  • Shortest routes: a map app keeps picking the closest place it hasn't visited yet.
  • Booking meeting rooms: pick the meeting that ends earliest, and more meetings fit.
  • Cabling an office network: always add the cheapest cable that connects something new.

For these problems, people have proved that the greedy rule gives the best answer. For a new problem, test it before you trust it.

Try it yourself

Change the amount to 47 cents with the 10, 5, 2, 1 till, and count the coins before you run it.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 20 of 21

Previous
The Sliding Window Technique: One In, One Out
Next post
Dynamic Programming: Work It Out Once, Write It Down, Read It Back

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

Big-O: Reading Cost From Code, With Handshakes and a Guest Book

Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.

Recursion: Russian Dolls, the Base Case and the Call Stack

Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.

Linear vs Binary Search: Page by Page, or Open in the Middle

Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.

Insertion Sort: Take the Next Card and Slide It Left Until It Fits

Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.

On this page

  • Grab the biggest coin that fits
  • Greedy change in Python
  • Step by step
  • A full till
  • Breaking it: a strange set of coins
  • When can you trust greedy?
  • What it costs
  • Where you meet greedy
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.