DSA · Patterns, not puzzles

When should you use greedy instead of dynamic programming?

Mediumgreedydynamic-programmingoptimizationUpdated Oct 2026
Quiz this track

Short answer

Use greedy when a locally best choice is provably part of some global optimum and cannot be undone by later choices. Use dynamic programming when choices interact and a locally good choice can block a better overall solution.

Greedy is faster and simpler, but it needs a correctness argument. The usual proof is an exchange argument: show that any optimal solution can be transformed to include the greedy choice without becoming worse. Without that argument, a greedy solution is just a guess.

js
function coinChange(coins, amount) {
  const dp = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (let value = 1; value <= amount; value++) {
    for (const coin of coins) {
      if (coin <= value) {
        dp[value] = Math.min(dp[value], dp[value - coin] + 1);
      }
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}
With coins such as 1, 3 and 4, a greedy choice of the largest coin fails for amount 6. DP finds 3 + 3.

Signals for each approach

  • Greedy: interval scheduling by earliest finish, Huffman coding, minimum spanning trees
  • DP: knapsack, coin change with arbitrary denominations, edit distance
  • Greedy needs an exchange argument or a matroid-style structure
  • DP is safer when choices can conflict across steps
  • If a greedy solution is wrong on a small counterexample, switch to DP

A useful interview move is to try a greedy idea, find a counterexample, then explain why DP is needed. That shows you can evaluate a strategy rather than pattern-match a topic name.

Greedy is not automatically wrong because it is simple, and DP is not automatically better because it is general. The proof and the constraints decide.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Give a counterexample where greedy coin change fails.
  2. 2How do you prove a greedy algorithm is correct?
  3. 3Why does interval scheduling by earliest finish work?
  4. 4When is a greedy solution acceptable without a formal proof in an interview?

Say it in the interview

I use greedy when I can argue that taking the locally best option never prevents an optimal solution. If choices interact, as in knapsack with arbitrary weights, I use dynamic programming. A good test is to try a small counterexample: greedy coin change fails with coins 1, 3 and 4 for amount 6. If I cannot justify the greedy choice, I prefer DP and explain the state.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.