Sub topic 25
Choosing between greedy and dynamic programming in GATE questions
This chapter assumes you know the greedy-choice property, optimal substructure, overlapping subproblems, and the exchange argument from earlier chapters. It also assumes you can read Python. Here we turn those ideas into a fast decision procedure for exam questions.
The core test
Both paradigms need optimal substructure: an optimal solution contains optimal solutions to subproblems. They differ in what happens at each step.
- Greedy commits to one choice and never revisits it. This is correct only if the greedy-choice property holds, meaning some optimal solution contains that choice. An exchange argument proves it.
- Dynamic programming (DP) tries every choice at each step and keeps the best subresult. It works when subproblems overlap, so a table avoids recomputation.
The question to ask is: "Can I prove that the locally best choice is part of some optimal solution?" If yes, greedy is usually faster. If you can't prove it, or you find a counterexample, use DP.
Pairs that GATE likes to contrast
Examiners often present two problems that look alike but need different methods.
| Problem | Method | Why | Typical time |
|---|---|---|---|
| Activity selection | Greedy (earliest finish) | Exchange argument works | O(n log n) |
| Fractional knapsack | Greedy (value/weight ratio) | Items are divisible | O(n log n) |
| 0/1 knapsack | DP | Ratio greedy can fail | O(nW) |
| Job sequencing with deadlines | Greedy (profit order) | Matroid-like structure | O(n²) simple |
| Huffman coding | Greedy (merge two smallest) | Exchange argument on leaves | O(n log n) |
| Coin change, canonical coin systems | Greedy | Works only for special coin sets | O(k) after sorting |
| Coin change, arbitrary coins | DP | Greedy can fail | O(n·amount) |
| LCS, edit distance, matrix chain | DP | Choices interact | O(mn), O(mn), O(n³) |
| Dijkstra | Greedy | Needs non-negative weights | O((V+E) log V) |
| Floyd-Warshall | DP | All pairs, negative edges allowed | O(V³) |
The O(nW) bound for 0/1 knapsack is pseudo-polynomial. It is polynomial in the numeric value W, not in the number of bits needed to write W. GATE sometimes asks this directly.
A counterexample you can run
Coin change with coins 1, 3, 4 and amount 6 shows greedy failing. Greedy takes 4, then 1, then 1, which is 3 coins. The optimum is 3 + 3, which is 2 coins.
def greedy_coins(coins, amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count if amount == 0 else None
def dp_coins(coins, amount):
INF = float('inf')
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp[amount] if dp[amount] != INF else None
print(greedy_coins([1, 3, 4], 6)) # 3
print(dp_coins([1, 3, 4], 6)) # 2The same effect appears in knapsack. Take weights 10, 20, 30, values 60, 100, 120, and capacity 50.
- Fractional version: take items 1 and 2 (value 160), then 20/30 of item 3 (value 80). Total is 240.
- 0/1 version, ratio greedy: items 1 and 2 give 160, and item 3 no longer fits.
- 0/1 version, optimum: items 2 and 3 give 220.
The ratio greedy fails because it cannot split the last item. Unused capacity is wasted.
Common errors
- Choosing greedy because the problem says "maximum" or "minimum". Almost every optimization question says this. Check the choice property, not the wording.
- Using a wrong greedy key. Activity selection sorted by start time, or by shortest duration, fails. Only earliest finish time is correct.
- Applying Dijkstra with negative edges. A settled vertex can later get a shorter distance through a negative edge. Use Bellman-Ford, or Floyd-Warshall for all pairs.
- Assuming DP means exponential choices are avoided by magic. DP is fast only when the number of distinct subproblems is polynomial. Count the table cells and the work per cell.
- Forgetting that coin systems like 1, 5, 10, 25 are special. Greedy works there, but not for every set.
Quick strategy for exam questions
- Look for a sorting key or a priority queue in the options. That points to greedy.
- Look for a recurrence with
maxorminover several earlier cells. That points to DP. - Test the greedy rule on a three-item case where a big item competes with two small ones.
- State the cost: sort plus one pass for greedy, cells times transition cost for DP.
Exercise
A shop has coin denominations 1, 6, and 10. For amount 12, what does the greedy method (largest coin first) return, and what does DP return? Which method should you use for this coin set?
Show answer
Greedy takes 10, then 1, then 1, for 3 coins. DP finds 6 + 6, for 2 coins. Use DP, because this coin set has no greedy-choice property.
Exercise
Why does the 0/1 knapsack DP running in O(nW) not prove that 0/1 knapsack is solvable in polynomial time?
Show answer
The running time grows with the value of W, not with the number of bits needed to write W. If W has b bits, W can be about 2^b, so the algorithm is exponential in the input length. It is pseudo-polynomial.
Exercise
Dijkstra's algorithm is greedy, yet it fails on a graph with an edge of weight -2. State the reason in one sentence.
Show answer
Dijkstra's greedy choice assumes that a settled vertex has its final shortest distance, but a negative edge can later give a shorter path to that vertex and so break the assumption.