← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Greedy Algorithms

algorithms PHP 5.0+ Intermediate

Also Known As

greedy choice local optimum

TL;DR

Algorithms that make the locally optimal choice at each step — fast and simple, but only produce the globally optimal solution for problems with the greedy choice property.

Explanation

A greedy algorithm selects the best available option at each step without reconsidering previous choices. It works when: the greedy choice is safe (local optimum leads to global optimum) and the problem has optimal substructure. Classic examples: coin change (if denominations allow), interval scheduling (sort by end time), Huffman coding, Kruskal/Prim for minimum spanning trees. Fails for: general coin change (e.g. coins {1,3,4} — greedy for 6 gives {4,1,1} not optimal {3,3}).

Diagram

flowchart TD
    PROBLEM[Optimisation problem] --> CHOICE[Make locally optimal choice<br/>at each step]
    CHOICE --> IRREV[Never reconsider<br/>irrevocable decision]
    IRREV --> NEXT[Move to next subproblem]
    NEXT -->|done?| SOLUTION[Global solution]
    subgraph Works For
        COIN[Coin change - large denominations first]
        HUFFMAN[Huffman coding]
        DIJKSTRA[Dijkstra shortest path]
        PRIM[Prim minimum spanning tree]
    end
    subgraph Does NOT Work For
        KNAPSACK[0-1 Knapsack - needs DP]
        TSP[Travelling Salesman]
    end
style SOLUTION fill:#238636,color:#fff
style KNAPSACK fill:#f85149,color:#fff
style TSP fill:#f85149,color:#fff

Common Misconception

Greedy algorithms always find the optimal solution — they only work when the greedy choice property holds; many problems (knapsack, TSP) require dynamic programming or backtracking.

Why It Matters

Greedy algorithms are O(n log n) or faster — recognising when a greedy approach is correct avoids the complexity of dynamic programming for problems that don't need it.

Common Mistakes

  • Applying greedy to problems where it doesn't hold — coin change with arbitrary denominations requires DP.
  • Not sorting before applying greedy — most greedy algorithms require the input in a specific order.
  • Confusing greedy with DP — if a problem has overlapping subproblems, DP is required; if choices are independent, greedy may work.
  • Not proving the greedy choice property — assuming greedy works without verifying leads to subtly wrong solutions.

Code Examples

✗ Vulnerable
// Greedy coin change fails for non-standard denominations:
function greedyChange(int $amount, array $coins): array {
    rsort($coins); // Sort descending
    $result = [];
    foreach ($coins as $coin) {
        while ($amount >= $coin) { $result[] = $coin; $amount -= $coin; }
    }
    return $result;
}
// greedyChange(6, [1,3,4]) returns [4,1,1] — 3 coins
// Optimal: [3,3] — 2 coins. Greedy fails here.
✓ Fixed
// DP coin change — always optimal:
function dpChange(int $amount, array $coins): int {
    $dp = array_fill(0, $amount + 1, PHP_INT_MAX);
    $dp[0] = 0;
    for ($i = 1; $i <= $amount; $i++) {
        foreach ($coins as $coin) {
            if ($coin <= $i && $dp[$i - $coin] !== PHP_INT_MAX) {
                $dp[$i] = min($dp[$i], $dp[$i - $coin] + 1);
            }
        }
    }
    return $dp[$amount] === PHP_INT_MAX ? -1 : $dp[$amount];
}

Added 15 Mar 2026
Edited 22 Mar 2026
Views 25
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping W 0 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 0 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Perplexity 8 Amazonbot 6 Ahrefs 2 Unknown AI 2 Majestic 1 Google 1 SEMrush 1
crawler 21
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Medium
⚡ Quick Fix
Greedy works when a locally optimal choice always leads to a global optimum — verify this property before using greedy; use dynamic programming when subproblems overlap
📦 Applies To
PHP 5.0+ web cli
🔗 Prerequisites
🔍 Detection Hints
Scheduling optimisation or resource allocation problem solved suboptimally where greedy would be exact
Auto-detectable: ✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Function Tests: Update

✓ schema.org compliant