---
title: "Greedy Algorithms Explained with Examples"
url: https://www.khanwaseem.com/blog/data-structure-and-algorithm/greedy-algorithms
author: "khan Waseem"
published: 2026-12-04
updated: 2026-12-04
topics: ["Data Structure and Algorithm", "Blog"]
description: "Learn how greedy algorithms work, when the greedy choice gives the best answer and when it fails, with tested JavaScript solutions for coins, meetings, knapsack and jump game problems."
---

# Greedy Algorithms Explained with Examples

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [What Is a Greedy Algorithm?](#what-is-a-greedy-algorithm)
- [When Does Greedy Work?](#when-does-greedy-work)
- [Problem 1: Making Change with Coins](#problem-1-making-change-with-coins)[Where greedy fails:](#where-greedy-fails)

- [Problem 2: Maximum Meetings in One Room](#problem-2-maximum-meetings-in-one-room)[Why the other rules fail:](#why-the-other-rules-fail)
- [Testing against brute force:](#testing-against-brute-force)

- [Problem 3: Fractional Knapsack](#problem-3-fractional-knapsack)[The 0/1 version breaks greedy:](#the-01-version-breaks-greedy)

- [Problem 4: Jump Game](#problem-4-jump-game)[Fewest jumps:](#fewest-jumps)

- [Problem 5: Assign Cookies](#problem-5-assign-cookies)
- [Greedy vs Dynamic Programming:](#greedy-vs-dynamic-programming)
- [Famous Greedy Algorithms:](#famous-greedy-algorithms)
- [Common Mistakes to Avoid:](#common-mistakes-to-avoid)[1. Trusting a greedy rule without proof:](#1-trusting-a-greedy-rule-without-proof)
- [2. Sorting by the wrong key:](#2-sorting-by-the-wrong-key)
- [3. Mixing up similar problems:](#3-mixing-up-similar-problems)
- [4. Changing the input by accident:](#4-changing-the-input-by-accident)

- [Conclusion:](#conclusion)

## Introduction:

In [Dynamic Programming for Beginners](https://blog.khanwaseem.com/dynamic-programming/) we solved problems by trying every option and remembering the results. Dynamic programming is powerful, but it can be slow and use a lot of memory.

A **greedy algorithm** takes a much simpler approach: at every step, it picks the option that looks **best right now**, and it never goes back to change that choice. No trying every combination, no table of results.

Sometimes this simple idea gives the perfect answer, very fast. Sometimes it gives a wrong answer. The real skill is knowing which case you are in. In this lesson you will learn how greedy algorithms work, solve five classic problems, and see exactly where greedy breaks. All the code is JavaScript, and every output shown was produced by running it.

## What Is a Greedy Algorithm?

Think about giving change at a shop. If you owe a customer ₹289, you don’t think hard. You hand over the biggest note that fits (₹200), then the biggest that fits the rest (₹50), and so on. That is a greedy algorithm.

Every greedy algorithm follows the same steps:

- Decide what “best right now” means (biggest coin, earliest finish time, best value per kg).

- Usually, **sort** the input by that rule.

- Go through the items once, taking each one if it still fits.

Because of the sort, most greedy solutions run in **O(n log n)** time, and the loop after the sort is just O(n).

## When Does Greedy Work?

A greedy algorithm gives the correct answer only when the problem has two properties:

- **Greedy choice property:** a best overall answer can always be built by making the locally best choice first. You never need to “sacrifice” now to win later.

- **Optimal substructure:** after you make that choice, what is left is a smaller version of the same problem. (Dynamic programming needs this property too.)

If you are not sure the first property holds, look for a counter-example, or compare your greedy answer with a brute-force answer on many small random inputs. We will do both below.

## Problem 1: Making Change with Coins

Give change for an amount using the fewest coins:

```javascript
function greedyCoins(coins, amount) {
  const sorted = [...coins].sort((a, b) => b - a); // biggest first
  const used = [];
  for (const coin of sorted) {
    while (amount >= coin) {
      amount -= coin;
      used.push(coin);
    }
  }
  return amount === 0 ? used : null;
}

console.log(greedyCoins([1, 2, 5, 10, 20, 50, 100, 200, 500], 289));
// [200, 50, 20, 10, 5, 2, 2]Code language: JavaScript (javascript)
```

Seven coins and notes, and that is the best possible answer. For the Indian rupee (and most real currencies), greedy always works, because the denominations were designed that way.

### Where greedy fails:

Now try a made-up coin system with coins 1, 3 and 4, and an amount of 6:

```javascript
console.log(greedyCoins([1, 3, 4], 6)); // [4, 1, 1]  -> 3 coinsCode language: JavaScript (javascript)
```

Greedy takes the 4 first, then needs two 1s. But **3 + 3** uses only **2 coins**. Taking the biggest coin first was a mistake that greedy can never undo.

Dynamic programming finds the true answer because it checks every option:

```javascript
function minCoinsDP(coins, amount) {
  const dp = Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (let a = 1; a <= amount; a++) {
    for (const c of coins) {
      if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);
    }
  }
  return dp[amount];
}

console.log(minCoinsDP([1, 3, 4], 6)); // 2Code language: JavaScript (javascript)
```

This is the most important lesson about greedy algorithms: **a greedy solution that “looks right” can still be wrong.** Always check.

## Problem 2: Maximum Meetings in One Room

You have one meeting room and a list of meetings with start and end times. Fit in as many meetings as possible, with no overlaps. (This is the classic **activity selection** problem.)

What should “best right now” mean? There are a few ideas:

- Earliest start time?

- Shortest meeting?

- **Earliest end time?**

The correct rule is **earliest end time**. A meeting that ends early leaves the most time free for the rest.

```javascript
function maxMeetings(meetings) {
  const sorted = [...meetings].sort((a, b) => a.end - b.end);
  const chosen = [];
  let lastEnd = -Infinity;

  for (const m of sorted) {
    if (m.start >= lastEnd) {
      chosen.push(m.name);
      lastEnd = m.end;
    }
  }
  return chosen;
}

const meetings = [
  { name: "A", start: 9, end: 12 },
  { name: "B", start: 9, end: 10 },
  { name: "C", start: 10, end: 11 },
  { name: "D", start: 11, end: 13 },
  { name: "E", start: 12, end: 14 },
  { name: "F", start: 13, end: 15 },
];

console.log(maxMeetings(meetings)); // ['B', 'C', 'D', 'F']Code language: JavaScript (javascript)
```

Four meetings, and no schedule can fit more.

### Why the other rules fail:

- **Earliest start:** if one meeting runs from 8 to 18, it starts first, gets picked, and blocks the whole day. With meetings 8–18, 9–10 and 10–11, “earliest start” picked only `['Long']`, while 9–10 and 10–11 fit two.

- **Shortest first:** with meetings P (9–12), Q (11–13) and R (12–15), the shortest one is Q, and it overlaps both others. “Shortest first” got only `['Q']`, while “earliest end” got `['P', 'R']`.

### Testing against brute force:

To be confident, we compared `maxMeetings` with a brute-force version that tries **every subset** of meetings, on 2,000 random lists of 8 meetings. The result was **0 mismatches**. This trick (a slow but obviously correct solution, plus random tests) is the best way to check a greedy idea before an interview or a production release.

## Problem 3: Fractional Knapsack

A thief has a bag that holds 50 kg. There are three sacks: rice (10 kg, worth ₹60), dal (20 kg, ₹100) and spices (30 kg, ₹120). The thief can take **part** of a sack. What is the most value he can carry?

Greedy rule: take the items with the best **value per kg** first.

- Rice: 60 / 10 = ₹6 per kg

- Dal: 100 / 20 = ₹5 per kg

- Spices: 120 / 30 = ₹4 per kg

```javascript
function fractionalKnapsack(items, capacity) {
  const sorted = [...items].sort((a, b) => b.value / b.weight - a.value / a.weight);
  let total = 0;
  for (const item of sorted) {
    if (capacity === 0) break;
    const take = Math.min(item.weight, capacity);
    total += item.value * (take / item.weight);
    capacity -= take;
  }
  return total;
}

const items = [
  { name: "rice", weight: 10, value: 60 },
  { name: "dal", weight: 20, value: 100 },
  { name: "spices", weight: 30, value: 120 },
];

console.log(fractionalKnapsack(items, 50)); // 240Code language: JavaScript (javascript)
```

All the rice (₹60), all the dal (₹100), and 20 of the 30 kg of spices (₹80): **₹240**, the best possible.

### The 0/1 version breaks greedy:

If the thief must take a whole sack or nothing (the **0/1 knapsack**), the same greedy rule fails. It takes rice and dal (₹160) and then the spices do not fit. But dal + spices = 50 kg exactly, worth **₹220**. Our test confirmed it: greedy gave `160`, dynamic programming gave `220`. A tiny change to the problem completely changes which technique you need.

## Problem 4: Jump Game

You are given an array where each number is the **maximum jump** from that position. Starting at index 0, can you reach the last index?

The greedy idea: walk through the array and keep track of the **farthest** index you can reach so far. If you ever stand on an index beyond that, you are stuck.

```javascript
function canJump(nums) {
  let farthest = 0;
  for (let i = 0; i < nums.length; i++) {
    if (i > farthest) return false;
    farthest = Math.max(farthest, i + nums[i]);
  }
  return true;
}

console.log(canJump([2, 3, 1, 1, 4])); // true
console.log(canJump([3, 2, 1, 0, 4])); // falseCode language: JavaScript (javascript)
```

In the second array, every path lands on the 0 at index 3, so index 4 is never reachable. One pass, **O(n)** time, **O(1)** space.

### Fewest jumps:

A slightly harder version asks for the **minimum number of jumps**. The greedy trick is to think in “levels”, like the [BFS traversal](https://blog.khanwaseem.com/bfs-and-dfs-graph-traversal/) from the last DSA lesson: all indexes you can reach with one jump, then with two, and so on.

```javascript
function minJumps(nums) {
  let jumps = 0, currentEnd = 0, farthest = 0;
  for (let i = 0; i < nums.length - 1; i++) {
    farthest = Math.max(farthest, i + nums[i]);
    if (i === currentEnd) { // we used up the reach of the current jump
      jumps++;
      currentEnd = farthest;
    }
  }
  return jumps;
}

console.log(minJumps([2, 3, 1, 1, 4])); // 2  (index 0 -> 1 -> 4)
console.log(minJumps([1, 1, 1, 1]));    // 3Code language: JavaScript (javascript)
```

## Problem 5: Assign Cookies

Each child has a **greed** value (the smallest cookie that makes them happy), and you have cookies of different sizes. Each child gets at most one cookie. How many children can you make happy?

Greedy rule: give the **smallest cookie that is big enough** to the **least greedy** child. Big cookies stay available for greedier children.

```javascript
function assignCookies(greed, cookies) {
  greed = [...greed].sort((a, b) => a - b);
  cookies = [...cookies].sort((a, b) => a - b);
  let child = 0;
  for (const size of cookies) {
    if (child < greed.length && size >= greed[child]) child++;
  }
  return child;
}

console.log(assignCookies([1, 2, 3], [1, 1]));    // 1
console.log(assignCookies([1, 2], [1, 2, 3]));    // 2
console.log(assignCookies([3, 1, 2], [2, 1, 4])); // 3Code language: JavaScript (javascript)
```

This uses the **two pointers** pattern from an earlier lesson ([Two Pointers and Sliding Window](https://blog.khanwaseem.com/two-pointers-and-sliding-window/)): one pointer over children, one over cookies, both moving forward only.

## Greedy vs Dynamic Programming:

- **Greedy** makes one choice per step and never looks back. It is fast and uses little memory, but it is only correct for problems with the greedy choice property.

- **Dynamic programming** considers every choice and keeps the best. It is slower and uses more memory, but it works for many more problems.

A good way to decide: first look for a simple greedy rule. Then try hard to break it with a small example. If you can’t break it (and a brute-force test agrees), use greedy. If you can, switch to dynamic programming.

## Famous Greedy Algorithms:

You will meet greedy ideas inside many well-known algorithms:

- **Dijkstra’s shortest path:** always visit the closest unvisited node next.

- **Prim’s and Kruskal’s algorithms:** build a minimum spanning tree by always adding the cheapest safe edge.

- **Huffman coding:** build a compression code by always merging the two least frequent symbols (used in ZIP files and JPEG images).

- **Interval scheduling:** the meeting room problem above, used in calendars and CPU scheduling.

## Common Mistakes to Avoid:

### 1. Trusting a greedy rule without proof:

The coin example shows that a natural rule can be wrong. Always look for a counter-example.

### 2. Sorting by the wrong key:

In the meeting problem, sorting by start time or by length both fail. Only end time works. The choice of key **is** the algorithm.

### 3. Mixing up similar problems:

Fractional knapsack is greedy. 0/1 knapsack is not. Read the problem carefully.

### 4. Changing the input by accident:

`array.sort()` sorts in place. In the code above we copy first with `[...array]` so the caller’s data is not changed.

## Conclusion:

A greedy algorithm builds an answer one step at a time, always taking the option that looks best right now and never undoing it. When the problem has the greedy choice property, this gives the best answer in about O(n log n) time with very little code, as we saw with meeting rooms, fractional knapsack, jump game and assign cookies. When it doesn’t, like coins 1, 3, 4 or the 0/1 knapsack, greedy quietly returns a wrong answer, and you need dynamic programming.

The habit to build: pick a greedy rule, try to break it with a small example, and test it against brute force.

In the next DSA lesson, we will learn **Dijkstra’s Shortest Path Algorithm**, one of the most famous greedy algorithms of all.

### Related posts:

[JavaScript and Cookies](https://blog.khanwaseem.com/javascript-and-cookies/)
[Dynamic Programming for Beginners](https://blog.khanwaseem.com/dynamic-programming/)
[Heap Sort](https://blog.khanwaseem.com/heap-sort/)
[BFS and DFS: Graph Traversal Explained](https://blog.khanwaseem.com/bfs-and-dfs-graph-traversal/)

Powered by [YARPP](https://yarpp.com).
