AlgoTales · Roadmap

Greedy strategy

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A greedy strategy makes the best-looking choice at each step and never looks back. When the problem has the right shape it gives the best answer with very little work; when it does not, it gives a decent but wrong one, so knowing the difference matters.

Practical use cases

  • Web app: Cheapest cable first for an office network. A planning tool picks the cheapest available link that connects a new office, repeatedly. For this kind of problem the greedy choice is provably optimal, and the tool answers instantly. The team also gets a result they can explain in one sentence: "we always added the cheapest link that connected something new".
  • Web app: Booking the most meetings in a room. A room-booking page accepts the meeting that ends earliest, then the next that fits. A small loop yields the largest number of meetings, with no complicated search.
  • Web app: Compressing files for download. A site zips exports for download. Compression assigns short codes to the most common symbols, built greedily, so a report of 5 MB shrinks to about 2 MB.
  • System: Where greedy fails. Giving change with odd coin values, or packing a bag with whole items, can fool greedy choices into a worse answer, so engineers check the problem first or use dynamic programming.

The story: The Hungry Mira and the Mithai Tray

At Zoya's wedding, Mira was handed an empty plate and one rule: "You may pass the mithai counters only once, no going back!" Counter one had a barfi. Counter two had a laddoo. Far at the end, rumour said, was a giant jalebi tower.

Mira did the simplest thing a hungry kid can do: at every counter she grabbed the biggest sweet in front of her. No planning, no looking ahead. She was happy, her plate filled fast, and she never worried about the past.

Her brother Kabir used the same trick to pay for chai. To make ₹30 with ₹10, ₹5 and ₹1 coins he simply gave the biggest coin that still fits again and again: 10, 10, 10. Perfect, and super quick! That is a greedy algorithm: pick the best-looking option right now, never undo it.

But at the last counter Mira saw the jalebi tower, and her plate was already full of small stuff. Greedy had trapped her. Mrs. Sharma explained: "Greedy is wonderful when you can prove a locally best choice never spoils the best final answer. When you cannot, check with a different method." Today you learn to love greedy and to doubt it, both.

How to spot this problem, and where you need it

You face a problem with many choices in a row and want a quick, simple loop to make them, but need to know if grabbing the best-looking option each time is actually safe.

Signs you need it

  • The problem asks for a maximum or minimum, and sorting by one simple rule (earliest end, cheapest, best ratio) seems to give the answer.
  • After making a choice, the rest of the problem looks like a smaller version of the same problem.
  • A full search over all combinations would be huge, but a hand example suggests the local best is always right.

Where to use it in a project

  • Scheduling, packing and budgeting features where sorting by a rule and scanning once gives the result.
  • Compression, routing and network planning code built on known greedy algorithms.

The solution

Find a rule that ranks the choices (earliest finish, lowest cost, highest value per unit). Sort by it, then go through the choices, taking each one if it still fits the constraints. Before trusting it, test the rule on small tricky cases or argue that taking the best now never blocks a better whole answer. If a counter-example appears, switch to dynamic programming or backtracking.

Payoff: Before: searching every combination of 30 bookings, billions of cases. After: sort plus one pass, about 30 steps, with the best answer.

Explain it like I am 8

Greedy means: always grab the best thing you can see right now, and never change your mind. It is like picking the biggest slice of cake at every turn. Sometimes that makes the biggest pile of cake. Sometimes a tiny slice was hiding a giant surprise behind it!

How it works, step by step

  1. Define "best right now": biggest, smallest, earliest, cheapest. This rule is the whole algorithm.
  2. Often sort first so that the best choice is always at the front.
  3. Take the best choice that still keeps the answer valid, and lock it in. No undoing.
  4. Repeat with what is left until nothing is left to decide.
  5. Check it is safe: ask whether grabbing the best-looking choice could ever block a better overall answer. If yes, you need another tool, like dynamic programming.

The code in four languages

PHP

<?php
// A tiny tree: each node has a value and child nodes.
function node(int $v, array $kids = []): array { return ['v' => $v, 'kids' => $kids]; }

// Greedy: at each fork take the child with the biggest number.
function greedyPath(array $n): int {
    $total = $n['v'];
    while (count($n['kids']) > 0) {
        $best = $n['kids'][0];
        foreach ($n['kids'] as $kid) {
            if ($kid['v'] > $best['v']) $best = $kid;   // locally best choice
        }
        $n = $best;
        $total += $n['v'];
    }
    return $total;
}

// Careful (but slower) way: try every path and keep the best total.
function bestPath(array $n): int {
    $best = 0;
    foreach ($n['kids'] as $kid) $best = max($best, bestPath($kid));
    return $n['v'] + $best;
}

$tree = node(10, [node(5, [node(1), node(2)]), node(3, [node(100)])]);
echo "Greedy: " . greedyPath($tree) . PHP_EOL;   // 17
echo "Best:   " . bestPath($tree) . PHP_EOL;     // 113  (greedy missed it!)

JavaScript

// A tiny tree: each node has a value and child nodes.
const node = (v, kids = []) => ({ v, kids });

// Greedy: at each fork take the child with the biggest number.
function greedyPath(n) {
  let total = n.v;
  while (n.kids.length > 0) {
    let best = n.kids[0];
    for (const kid of n.kids) {
      if (kid.v > best.v) best = kid;   // locally best choice
    }
    n = best;
    total += n.v;
  }
  return total;
}

// Careful (but slower) way: try every path and keep the best total.
function bestPath(n) {
  let best = 0;
  for (const kid of n.kids) best = Math.max(best, bestPath(kid));
  return n.v + best;
}

const tree = node(10, [node(5, [node(1), node(2)]), node(3, [node(100)])]);
console.log("Greedy: " + greedyPath(tree));   // 17
console.log("Best:   " + bestPath(tree));     // 113 (greedy missed it!)

Java

import java.util.*;

public class Main {
    // A tiny tree: each node has a value and child nodes.
    record Node(int v, List<Node> kids) {}

    static Node node(int v, Node... kids) { return new Node(v, List.of(kids)); }

    // Greedy: at each fork take the child with the biggest number.
    static int greedyPath(Node n) {
        int total = n.v();
        while (!n.kids().isEmpty()) {
            Node best = n.kids().get(0);
            for (Node kid : n.kids()) {
                if (kid.v() > best.v()) best = kid;   // locally best choice
            }
            n = best;
            total += n.v();
        }
        return total;
    }

    // Careful (but slower) way: try every path and keep the best total.
    static int bestPath(Node n) {
        int best = 0;
        for (Node kid : n.kids()) best = Math.max(best, bestPath(kid));
        return n.v() + best;
    }

    public static void main(String[] args) {
        Node tree = node(10, node(5, node(1), node(2)), node(3, node(100)));
        System.out.println("Greedy: " + greedyPath(tree));   // 17
        System.out.println("Best:   " + bestPath(tree));     // 113  (greedy missed it!)
    }
}

Go

package main

import "fmt"

// A tiny tree: each node has a value and child nodes.
type Node struct {
	v    int
	kids []Node
}

func node(v int, kids ...Node) Node { return Node{v, kids} }

// greedyPath: at each fork take the child with the biggest number.
func greedyPath(n Node) int {
	total := n.v
	for len(n.kids) > 0 {
		best := n.kids[0]
		for _, kid := range n.kids {
			if kid.v > best.v {
				best = kid // locally best choice
			}
		}
		n = best
		total += n.v
	}
	return total
}

// bestPath is the careful (but slower) way: try every path and keep the best total.
func bestPath(n Node) int {
	best := 0
	for _, kid := range n.kids {
		best = max(best, bestPath(kid))
	}
	return n.v + best
}

func main() {
	tree := node(10, node(5, node(1), node(2)), node(3, node(100)))
	fmt.Println("Greedy:", greedyPath(tree)) // 17
	fmt.Println("Best:  ", bestPath(tree))   // 113  (greedy missed it!)
}

Time: O(n) · Extra space: O(1). Greedy usually looks at each choice once, so it is fast, but only the right problems let it be correct.

Watch out for

  • Assuming greedy is always right. A rule that "feels" smart must be checked, for example by comparing with a slow brute force on small examples.
  • Choosing the wrong "best". For scheduling, "shortest meeting first" and "earliest finish first" are different rules and only one is correct.
  • Forgetting to sort first, so the "best" choice is not actually at the front.

Quick check

  1. What does a greedy algorithm do at each step?
    • Tries every possibility
    • Always picks randomly
    • Takes the best-looking choice right now and never undoes it
  2. When is greedy guaranteed to give the best answer?
    • When a locally best choice can be shown to lead to a globally best answer
    • Always
    • Only when the input is sorted
  3. In our tree, why did greedy get only 17?
    • It ignored the root
    • The bigger-looking 5 led away from the huge 100
    • It added numbers wrongly