Greedy and dynamic programmingsenior8+ years

A pricing engine picks the largest applicable discount tier first, then the next largest, to maximise total savings on an order — and it produces a demonstrably suboptimal answer on a specific combination of tiers, even though the same greedy approach worked correctly on every case anyone tested. How do you tell, in general, whether a problem like this can be solved greedily, and if it can't, what's the actual fix?

Greedy isn't a technique you apply to a problem — it's a property a problem either has or doesn't, and the test is a specific question: does taking the locally best step always leave a situation from which the overall best answer is still reachable? The classic counterexample is coin change with denominations 25, 10 and 1 making 30 — greedy takes the 25 first, then five 1-cent coins, for six coins total, when three 10s would have been optimal; taking the 25 destroyed the 10-10-10 answer, and nothing in the greedy algorithm itself can detect that it just made an irrecoverable mistake. The pricing engine's tier-stacking is almost certainly the same shape: taking the largest tier first can make a combination of two smaller tiers unreachable, even though that combination would have saved more overall. When greedy doesn't provably hold, the fix isn't a smarter greedy rule — it's dynamic programming, which considers all the choices rather than committing to one, but avoids the exponential blowup of trying literally everything by never solving the same subproblem twice.

The lesson behind it →