Algorithms · Greedy

Greedy algorithms in action

Four problems where a greedy choice does the work. For three of them, the greedy choice property holds and greedy is always optimal. For the fourth, it depends on the problem's details. Each section has a lab that steps through the C++.

Reminder from the first greedy page: greedy is optimal when the problem has the greedy choice property (some optimal solution starts with the greedy choice) and optimal substructure (what is left after that choice is a smaller problem of the same kind). For each problem below, ask: what is the greedy choice, and why can't it lead us astray?

Coin change

Problem: make an amount using the fewest coins, with unlimited coins of each denomination.

Greedy choice: take the largest coin that is not more than what is left, and repeat. With US coins (25, 10, 5, 1) this is always optimal: 63¢ is 25 + 25 + 10 + 1 + 1 + 1, six coins.

But it depends on the coins. With coins 1, 3 and 4, greedy makes 6 as 4 + 1 + 1 (three coins), while 3 + 3 uses two. Coin systems where greedy always works are called canonical; US and euro coins are designed to be canonical.

Making change

What is happening

change.cpp

    Stop and think
    With coins 25, 20, 10, 5, 1, find an amount where greedy is not optimal.

    40: greedy takes 25 + 10 + 5 (three coins), but 20 + 20 uses two. 30 is not a counterexample: greedy takes 25 + 5 and that is already the best. Choose these coins in the lab and try 40.

    Why does greedy work for US coins? Give the idea.

    An optimal answer never uses more than 4 pennies (5 pennies could be a nickel), never 2 nickels (a dime), and never more than 2 dimes (3 dimes = 25 + 5, one coin fewer). With those limits, pennies, nickels and dimes can add up to at most 24¢. So any amount of 25¢ or more must use a quarter, which is exactly the greedy choice. The same reasoning works down the line.

    How do you find the fewest coins when greedy fails?

    Dynamic programming: for every amount a from 1 up to the target, best[a] = 1 + the smallest best[a − c] over all coins c ≤ a. That is how the lab computes the "fewest possible" answer. It takes O(amount × number of coins) time, and works for any coins.

    Activity selection

    Problem: one room, many requested activities, each with a start and finish time. Schedule as many as possible with no two overlapping. An activity may start exactly when another finishes.

    Greedy choice: always take the activity that finishes earliest among those that still fit. Finishing early leaves the most time for everything else. Sort by finish time, then sweep once, taking each activity that starts no earlier than the last one you took finished.

    Other rules sound just as reasonable, such as "earliest start" or "shortest first", but they fail. Try them in the lab with the trap presets.

    Greedy rule

    Activities, in the order the rule considers them

    What is happening

    activities.cpp

      Stop and think
      Why is "earliest finish" safe? Sketch the exchange argument.

      Take any optimal schedule, and let f be the activity that finishes earliest overall. If the schedule does not include f, swap its first activity for f. f ends no later than the activity it replaced, so it cannot overlap anything after it, and the schedule has the same number of activities. So some optimal schedule starts with f: the greedy choice property. What remains is the same problem for the activities starting after f ends: optimal substructure.

      Find a set where "shortest first" fails, without using the lab.

      [0, 5), [4, 7) and [6, 11). The shortest, [4, 7), overlaps both others, so shortest-first schedules just 1 activity. Earliest finish takes [0, 5) and [6, 11): 2.

      What does the algorithm cost?

      O(n log n) for the sort, then O(n) for the single sweep. Each activity is looked at once and accepted or rejected immediately.

      Dijkstra's shortest paths

      Problem: in a graph with non-negative edge weights, find the shortest distance from a source vertex to every other vertex.

      Greedy choice: of the vertices not yet finished, take the one with the smallest tentative distance, and declare that distance final. Then relax its edges: for each neighbor v, if going through u gives a shorter route to v, update v's distance.

      Why can the choice be final? Any other route to u would have to leave the finished set through some unfinished vertex that is already at least as far away, and with no negative edges, the rest of that route can only add distance.

      The graph

      What is happening

      dijkstra.cpp

        Stop and think
        With the class weights, the edge A–B has weight 7, but Dijkstra reports dist(B) = 5. How?

        A → C → B costs 2 + 3 = 5. B starts at 7 after A is finished, then C (distance 2) is chosen next, and relaxing the edge C–B lowers B to 5. That is why a vertex's distance is only final once it is chosen, not when it is first reached.

        Why does a negative edge break Dijkstra?

        Suppose A–B is 2, A–C is 3, and C–B is −2. Dijkstra finishes B at distance 2 first, since 2 < 3. But A → C → B costs 3 + (−2) = 1. The greedy choice assumed no later path could get shorter, and a negative edge makes that false. (Bellman–Ford handles negative edges.)

        The code finds u by scanning every vertex. How do real implementations do it faster?

        With a min-priority queue (a heap) keyed by distance. Finding the closest vertex becomes O(log V) instead of O(V), and the total time becomes O((V + E) log V) instead of O(V²).

        Kruskal's minimum spanning tree

        Problem: connect every vertex of a weighted, undirected graph using a set of edges with the smallest total weight. The result has no cycles (a cycle's heaviest edge could be dropped), so it is a tree: a minimum spanning tree.

        Greedy choice: look at the edges from lightest to heaviest, and take an edge unless it would make a cycle with the edges already taken. To check that quickly, keep track of which vertices are already connected using a union-find structure: each vertex points toward a representative of its group, and an edge makes a cycle exactly when both ends already have the same representative.

        The graph

        What is happening

        kruskal.cpp

          Stop and think
          Why is taking the lightest edge that makes no cycle always safe?

          This is the cut property. Split the vertices into the group the edge's one end already belongs to and everything else. Any spanning tree must cross between the two groups somewhere, and the lightest crossing edge is the cheapest way to do it. If an optimal tree crossed with a heavier edge instead, swapping in the lighter one would give a tree that is no heavier.

          A tree on V vertices has V − 1 edges. How could Kruskal stop early?

          Stop as soon as V − 1 edges have been taken. Every later edge would join two vertices that are already connected, so it would be rejected anyway. In the class graph the fifth edge, B–D, completes the tree, and the last four edges are all rejections.

          Run Dijkstra from A and Kruskal on the class weights. Are the shortest-path tree and the minimum spanning tree the same?

          Not in general. Dijkstra's tree reaches E through C (A → C → E, 8) because that is the shortest route to E. The minimum spanning tree reaches E through D (edge D–E, weight 1), because it minimizes total edge weight, not the distance from A. The two greedy rules answer different questions.

          Summary

          ProblemGreedy choiceAlways optimal?Time
          Coin changelargest coin that fitsonly for canonical coin systemsO(coins + number used)
          Fractional knapsackbest value per unit of weightyesO(n log n)
          0/1 knapsack(any rule)no; use dynamic programming–
          Activity selectionearliest finish timeyesO(n log n)
          Dijkstraclosest unfinished vertexyes, if no negative edgesO((V + E) log V) with a heap
          Kruskallightest edge that makes no cycleyesO(E log E)
          Huffman codingjoin the two rarest treesyesO(n log n)