Skip to content

How to Fix Greedy Algorithm Wrong Choice Errors

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Greedy Algorithm Wrong Choice Errors. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Greedy Algorithm errors occur when the local optimum at each step does not lead to the global optimum. This happens when the problem does not have the greedy choice property, and a different approach (DP or exhaustive search) is needed.

Quick Fix

Wrong

std::vector<int> coinChange(std::vector<int> coins, int amount) {
    std::sort(coins.rbegin(), coins.rend());
    std::vector<int> result;
    for (int coin : coins) {
        while (amount >= coin) {
            amount -= coin;
            result.push_back(coin);
        }
    }
    return amount == 0 ? result : std::vector<int>();
}

For coins {1, 3, 4} and amount 6, greedy picks 4, 1, 1 (3 coins), but the optimal is 3, 3 (2 coins).

Right: DP solution

int coinChange(const std::vector<int>& coins, int amount) {
    std::vector<int> dp(amount + 1, amount + 1);
    dp[0] = 0;
    for (int i = 1; i <= amount; ++i) {
        for (int coin : coins) {
            if (coin <= i) {
                dp[i] = std::min(dp[i], 1 + dp[i - coin]);
            }
        }
    }
    return dp[amount] > amount ? -1 : dp[amount];
}

std::cout << coinChange({1, 3, 4}, 6);
2  (coins: 3+3)

Fix for interval scheduling

struct Interval { int start, end; };

// Greedy is correct for interval scheduling:
// pick earliest finish time
int maxIntervals(std::vector<Interval>& intervals) {
    std::sort(intervals.begin(), intervals.end(),
        [](const Interval& a, const Interval& b) {
            return a.end < b.end;
        });
    int count = 0, lastEnd = 0;
    for (const auto& interval : intervals) {
        if (interval.start >= lastEnd) {
            ++count;
            lastEnd = interval.end;
        }
    }
    return count;
}

Fix for fractional knapsack

struct Item { double weight, value, ratio; };

// Greedy IS correct for fractional knapsack
double fractionalKnapsack(std::vector<Item>& items, double capacity) {
    std::sort(items.begin(), items.end(),
        [](const Item& a, const Item& b) { return a.ratio > b.ratio; });
    double total = 0;
    for (const auto& item : items) {
        if (capacity >= item.weight) {
            total += item.value;
            capacity -= item.weight;
        } else {
            total += item.ratio * capacity;
            break;
        }
    }
    return total;
}

Prevention

  • Test the greedy choice on small counterexamples before implementing.
  • Know which problems greed is correct for: interval scheduling, fractional knapsack, Huffman coding, Dijkstra, MST.
  • Use DP when greedy fails: 0/1 knapsack, coin change (arbitrary denominations), edit distance.
  • Prove or verify that local optima lead to global optima.
  • Compare greedy results against brute force for small inputs.

DodaTech Tools

Doda Browser's algorithm comparator runs greedy, DP, and brute-force solutions side-by-side to detect greedy failures. DodaZIP archives optimization benchmarks. Durga Antivirus Pro detects greedy vulnerabilities in resource allocation algorithms.

Common Mistakes with greedy wrong choice

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. Mixing let bindings with <- bindings in do notation, producing type errors

These mistakes appear frequently in real-world ALGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

What is the greedy choice property?

A problem has the greedy choice property when a locally optimal choice leads to a globally optimal solution. This must be proven for each problem. Without it, greedy may produce suboptimal results.

Why does greedy work for fractional knapsack but not 0/1 knapsack?

Fractional knapsack allows taking fractions of items, so taking the highest value-per-weight at each step works. 0/1 knapsack requires taking entire items, where the optimal choice may not be immediately obvious.

How do I know if a problem should be solved with greedy or DP?

Try greedy first. If you can find a counterexample where greedy fails, use DP. Greedy is correct for problems with the exchange argument property (no matter what, swapping choices does not hurt).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro