Skip to content

15.1   Greedy algorithms

A greedy algorithm is a common way to solve optimization problems. At each decision point, it takes the option that looks best at that moment. The aim is to reach a globally optimal solution through locally optimal choices. Greedy algorithms are simple and efficient and have many practical applications.

Greedy algorithms and dynamic programming are both common approaches to optimization. They share some features, such as relying on optimal substructure, but they work differently.

  • Dynamic programming considers the full range of earlier decisions when making a decision at the current stage. It builds the solution to the current subproblem from solutions to earlier subproblems.
  • A greedy algorithm moves forward without reconsidering earlier decisions. Each greedy choice reduces the size of the remaining problem until the problem is solved.

Let's see how a greedy algorithm works by revisiting coin change, a problem we met in the section on unbounded knapsack.

Question

You are given \(n\) coin denominations. Denomination \(i\) is worth \(coins[i - 1]\), and the target amount is \(amt\). You may use each denomination repeatedly. What is the minimum number of coins needed to make the target amount? Return \(-1\) if the amount cannot be made.

Figure 15-1 shows the greedy strategy. Starting with the target amount, choose the largest coin that does not exceed the remaining amount. Repeat until the coins add up to the target.

Figure 15-1   Greedy strategy for coin change

Description of Figure 15-1: Coin change: making one greedy choice at a time

At each round, choose the largest denomination that does not exceed the remaining amount. The figure follows this process from 131 down to zero.

The target amount is 131, and the available denominations are [1, 5, 10, 20, 50, 100]. Each denomination can be used repeatedly. The figure states the greedy rule: “Always choose the coin closest to the remaining amount without exceeding it.” In each round, this is the largest denomination that fits.

From top to bottom, the rows show remaining amounts of 131, 31, 11, 1, and 0. The first four rows show the same denominations in the same order. They highlight 100, 20, 10, and 1 in turn, with the other denominations in gray. Dashed arrows link the choices in consecutive rows. The last row reaches zero and shows no candidate coins.

The remaining amount in each row already accounts for the coins used earlier. The highlighted coin is the next one, and its value is still included in the current amount. For example, the row for 31 has already deducted 100. Its highlighted 20 is deducted on the way to the row for 11. For each remaining amount, the table lists the coins already used, the next coin, and the amount left after that deduction.

Remaining amount, coins already used, and next choice
Current remaining amountCoins already usedNext coinAmount after deduction
131None10031
311002011
11100, 20101
1100, 20, 1010
0100, 20, 10, 1StopNo further deduction

The final 4 coins give 100 + 20 + 10 + 1 = 131. Denominations 5 and 50 are unused. For these denominations, 4 is also the minimum coin count. With other denominations, the greedy rule may use more coins than necessary.

Here is the implementation:

coin_change_greedy.py
def coin_change_greedy(coins: list[int], amt: int) -> int:
    """Greedy coin change"""
    # Assume the coins list is sorted
    i = len(coins) - 1
    count = 0
    # Make greedy choices until no amount remains
    while amt > 0:
        # Find the largest denomination that does not exceed the remaining amount
        while i > 0 and coins[i] > amt:
            i -= 1
        # Choose coins[i]
        amt -= coins[i]
        count += 1
    # Return -1 if no feasible solution was found
    return count if amt == 0 else -1
coin_change_greedy.cpp
/* Greedy coin change */
int coinChangeGreedy(vector<int> &coins, int amt) {
    // Assume the coins list is sorted
    int i = coins.size() - 1;
    int count = 0;
    // Make greedy choices until no amount remains
    while (amt > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > amt) {
            i--;
        }
        // Choose coins[i]
        amt -= coins[i];
        count++;
    }
    // Return -1 if no feasible solution was found
    return amt == 0 ? count : -1;
}
coin_change_greedy.java
/* Greedy coin change */
int coinChangeGreedy(int[] coins, int amt) {
    // Assume the coins list is sorted
    int i = coins.length - 1;
    int count = 0;
    // Make greedy choices until no amount remains
    while (amt > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > amt) {
            i--;
        }
        // Choose coins[i]
        amt -= coins[i];
        count++;
    }
    // Return -1 if no feasible solution was found
    return amt == 0 ? count : -1;
}
coin_change_greedy.cs
/* Greedy coin change */
int CoinChangeGreedy(int[] coins, int amt) {
    // Assume the coins list is sorted
    int i = coins.Length - 1;
    int count = 0;
    // Make greedy choices until no amount remains
    while (amt > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > amt) {
            i--;
        }
        // Choose coins[i]
        amt -= coins[i];
        count++;
    }
    // Return -1 if no feasible solution was found
    return amt == 0 ? count : -1;
}
coin_change_greedy.go
/* Greedy coin change */
func coinChangeGreedy(coins []int, amt int) int {
    // Assume the coins list is sorted
    i := len(coins) - 1
    count := 0
    // Make greedy choices until no amount remains
    for amt > 0 {
        // Find the largest denomination that does not exceed the remaining amount
        for i > 0 && coins[i] > amt {
            i--
        }
        // Choose coins[i]
        amt -= coins[i]
        count++
    }
    // Return -1 if no feasible solution was found
    if amt != 0 {
        return -1
    }
    return count
}
coin_change_greedy.swift
/* Greedy coin change */
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
    // Assume the coins list is sorted
    var i = coins.count - 1
    var count = 0
    var amt = amt
    // Make greedy choices until no amount remains
    while amt > 0 {
        // Find the largest denomination that does not exceed the remaining amount
        while i > 0 && coins[i] > amt {
            i -= 1
        }
        // Choose coins[i]
        amt -= coins[i]
        count += 1
    }
    // Return -1 if no feasible solution was found
    return amt == 0 ? count : -1
}
coin_change_greedy.js
/* Greedy coin change */
function coinChangeGreedy(coins, amt) {
    // Assume the coins array is sorted
    let i = coins.length - 1;
    let count = 0;
    // Make greedy choices until no amount remains
    while (amt > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > amt) {
            i--;
        }
        // Choose coins[i]
        amt -= coins[i];
        count++;
    }
    // Return -1 if no feasible solution was found
    return amt === 0 ? count : -1;
}
coin_change_greedy.ts
/* Greedy coin change */
function coinChangeGreedy(coins: number[], amt: number): number {
    // Assume the coins array is sorted
    let i = coins.length - 1;
    let count = 0;
    // Make greedy choices until no amount remains
    while (amt > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > amt) {
            i--;
        }
        // Choose coins[i]
        amt -= coins[i];
        count++;
    }
    // Return -1 if no feasible solution was found
    return amt === 0 ? count : -1;
}
coin_change_greedy.dart
/* Greedy coin change */
int coinChangeGreedy(List<int> coins, int amt) {
  // Assume the coins list is sorted
  int i = coins.length - 1;
  int count = 0;
  // Make greedy choices until no amount remains
  while (amt > 0) {
    // Find the largest denomination that does not exceed the remaining amount
    while (i > 0 && coins[i] > amt) {
      i--;
    }
    // Choose coins[i]
    amt -= coins[i];
    count++;
  }
  // Return -1 if no feasible solution was found
  return amt == 0 ? count : -1;
}
coin_change_greedy.rs
/* Greedy coin change */
fn coin_change_greedy(coins: &[i32], mut amt: i32) -> i32 {
    // Assume the coins list is sorted
    let mut i = coins.len() - 1;
    let mut count = 0;
    // Make greedy choices until no amount remains
    while amt > 0 {
        // Find the largest denomination that does not exceed the remaining amount
        while i > 0 && coins[i] > amt {
            i -= 1;
        }
        // Choose coins[i]
        amt -= coins[i];
        count += 1;
    }
    // Return -1 if no feasible solution was found
    if amt == 0 {
        count
    } else {
        -1
    }
}
coin_change_greedy.c
/* Greedy coin change */
int coinChangeGreedy(int *coins, int size, int amt) {
    // Assume the coins list is sorted
    int i = size - 1;
    int count = 0;
    // Make greedy choices until no amount remains
    while (amt > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > amt) {
            i--;
        }
        // Choose coins[i]
        amt -= coins[i];
        count++;
    }
    // Return -1 if no feasible solution was found
    return amt == 0 ? count : -1;
}
coin_change_greedy.kt
/* Greedy coin change */
fun coinChangeGreedy(coins: IntArray, amt: Int): Int {
    // Assume the coins list is sorted
    var am = amt
    var i = coins.size - 1
    var count = 0
    // Make greedy choices until no amount remains
    while (am > 0) {
        // Find the largest denomination that does not exceed the remaining amount
        while (i > 0 && coins[i] > am) {
            i--
        }
        // Choose coins[i]
        am -= coins[i]
        count++
    }
    // Return -1 if no feasible solution was found
    return if (am == 0) count else -1
}
coin_change_greedy.rb
### Greedy coin change ###
def coin_change_greedy(coins, amt)
  # Assume the coins list is sorted
  i = coins.length - 1
  count = 0
  # Make greedy choices until no amount remains
  while amt > 0
    # Find the largest denomination that does not exceed the remaining amount
    while i > 0 && coins[i] > amt
      i -= 1
    end
    # Choose coins[i]
    amt -= coins[i]
    count += 1
  end
  # Return -1 if no feasible solution was found
  amt == 0 ? count : -1
end
Visualize execution

Look how little code that takes! The greedy algorithm handles coin change in about ten lines.

15.1.1   Strengths and limitations of greedy algorithms

Greedy algorithms are straightforward to use, simple to implement, and often very efficient. In the code above, let \(\min(coins)\) be the smallest denomination. The greedy choice repeats at most \(amt / \min(coins)\) times, giving a time complexity of \(O(amt / \min(coins))\). This is an order of magnitude lower than the \(O(n \times amt)\) time complexity of the dynamic programming solution.

However, for some sets of denominations, the greedy algorithm fails to find an optimal solution. Figure 15-2 shows two examples.

  • Where greedy succeeds: \(coins = [1, 5, 10, 20, 50, 100]\). With these denominations, the greedy algorithm finds an optimal solution for any \(amt\).
  • Counterexample: \(coins = [1, 20, 50]\). Suppose \(amt = 60\). The greedy algorithm chooses \(50 + 1 \times 10\), using \(11\) coins. Dynamic programming finds the optimal combination \(20 + 20 + 20\), which takes only \(3\) coins.
  • Counterexample: \(coins = [1, 49, 50]\). Suppose \(amt = 98\). The greedy algorithm chooses \(50 + 1 \times 48\), using \(49\) coins. Dynamic programming finds the optimal combination \(49 + 49\), which takes only \(2\) coins.

Figure 15-2   Examples where greedy coin change misses the optimum

Description of Figure 15-2: Counterexamples to greedy coin change

Always choosing the largest usable denomination does not always give the fewest coins. Two counterexamples compare the greedy choices with globally better ways to make change.

In both examples, taking the largest denomination, 50, first leaves an amount that can be filled only with many coins of denomination 1. A different choice makes the same amount with fewer coins.

The figure has two rows. From left to right, each shows the available denominations, the target amount, a column labeled “Best greedy solution (local optimum),” and a column labeled “Best dynamic programming solution (global optimum).” Coin icons, plus signs, and multipliers represent the two solutions.

The table gives the denominations, target amounts, and solutions from the figure. The two coin-count columns give totals obtained by counting the coins in each solution. The original figure does not list those totals separately. The “best” label in the greedy column does not imply a global minimum.

Comparison of coin change solutions
DenominationsTarget amountGreedy solutionGreedy coin countOptimal solutionOptimal coin count
1, 20, 506050+1×101120×33
1, 49, 509850+1×484949×22

Greedy selection starts with 50, leaving 10 in the first example and 48 in the second. Each remainder is smaller than the corresponding second denomination, 20 or 49, so only coins of denomination 1 can fill it. The solutions on the right avoid 50 and use substantially fewer coins. This greedy rule cannot be relied on for arbitrary sets of denominations.

For coin change in general, a greedy algorithm cannot guarantee a global optimum and may give a very poor solution. Dynamic programming is a better fit for the general problem.

Greedy algorithms are generally useful in two situations.

  1. An optimal solution is guaranteed. A greedy algorithm is often the best choice here because it is usually more efficient than backtracking or dynamic programming.
  2. A near-optimal solution is possible. A greedy algorithm can still be useful here. For many complex problems, finding a global optimum is difficult, and an efficient way to get a good suboptimal solution is valuable.

15.1.2   Properties of greedy algorithms

What kinds of problems are good candidates for a greedy algorithm? In particular, when can we guarantee that it will find an optimal solution?

Greedy algorithms have stricter requirements than dynamic programming. Two properties of the problem are particularly important.

  • Greedy-choice property. A greedy algorithm can guarantee an optimal solution only if a locally optimal choice can always lead to a globally optimal solution.
  • Optimal substructure. An optimal solution to the original problem contains optimal solutions to its subproblems.

We covered optimal substructure in the chapter on dynamic programming. One point worth keeping in mind is that some problems admit a greedy solution even when their optimal substructure is hard to see.

Let's focus on how to recognize the greedy-choice property. The property is simple to state, but for many problems it is difficult to prove.

Take coin change. It is easy to give a counterexample that disproves the greedy-choice property, but proving the property is harder. What conditions must a set of denominations satisfy for greedy coin change to work? Intuition and examples may suggest an answer, but turning it into a rigorous mathematical proof is difficult.

Quote

One paper gives an \(O(n^3)\)-time algorithm for deciding whether greedy coin change is optimal for every amount with a given set of denominations.

Pearson, D. A polynomial-time algorithm for the change-making problem[J]. Operations Research Letters, 2005, 33(3): 231-234.

15.1.3   Steps for solving a problem with a greedy algorithm

Solving a problem with a greedy algorithm generally involves three steps.

  1. Analyze the problem. Identify the states, the objective to optimize, and the constraints. This step also comes up in backtracking and dynamic programming.
  2. Choose a greedy strategy. Decide how to make the greedy choice at each step. Each choice should reduce the size of the remaining problem until the entire problem is solved.
  3. Prove correctness. Typically, you need to show that the problem has the greedy-choice property and optimal substructure. This may require a mathematical proof, for example by induction or contradiction.

Choosing the greedy strategy is central to solving the problem, but it can be difficult for two main reasons.

  • Greedy strategies vary widely from one problem to another. For many problems, a little thought and experimentation reveal a straightforward strategy. For more complex problems, the strategy can be hard to spot, putting your problem-solving experience and algorithm design skills to the test.
  • Some greedy strategies are deceptive. You may feel confident in a strategy, implement it, and submit the code only to find that it fails some test cases. Such a strategy works only some of the time. Coin change is a classic example.

To establish correctness, we should give a rigorous mathematical proof of the greedy strategy, typically by contradiction or induction.

Finding a proof can itself be difficult. When we are stuck, we often debug the code against test cases, revising and checking the strategy one step at a time.

15.1.4   Common greedy algorithm problems

Greedy algorithms often solve optimization problems with the greedy-choice property and optimal substructure. Here are some typical examples.

  • Coin change. For certain sets of denominations, the greedy algorithm always gives an optimal solution.
  • Interval scheduling. Each task occupies a time interval, and you want to complete as many tasks as possible. Always choosing the available task that finishes earliest gives an optimal schedule.
  • Fractional knapsack. Given items and a weight limit, choose items to maximize total value without exceeding that limit. In some settings, always taking the item with the greatest value-to-weight ratio (value / weight) gives an optimal solution.
  • Buying and selling stock. Given a stock's historical prices, you may buy and sell multiple times. Once you buy, you must sell before buying again. The goal is to maximize profit.
  • Huffman coding. This greedy algorithm performs lossless data compression. To build a Huffman tree, repeatedly merge the two nodes with the lowest frequencies. The resulting tree minimizes the weighted path length (the encoded length).
  • Dijkstra's algorithm. In a graph with nonnegative edge weights, this greedy algorithm finds the shortest paths from a given source vertex to all other vertices.
Share your thoughts, questions, or suggestions in the comments.