How to Fix Greedy Algorithm Wrong Choice Errors
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
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro