Compare greedy and dynamic programming
Compare greedy and dynamic programming
A greedy algorithm chooses a locally preferred action without revisiting it. It is correct only when the problem structure supports that choice. Dynamic programming (DP) stores solutions to overlapping subproblems and combines them using a recurrence. For minimum coin count, greedy may fail for arbitrary denominations.
package main
import ( "fmt")
func greedy(a int, coins []int) (int, bool) { n := 0 for _, c := range coins { n += a / c a %= c } return n, a == 0}func main() { fmt.Println(greedy(6, []int{4, 3, 1}))}With positive denominations sorted descending, greedy takes 4+1+1. Yet 3+3 uses two coins. This is a counterexample to the greedy rule, even though its result is feasible. Greedy can be optimal for some systems but requires proof; the example assumes nonnegative amount and positive coins.
Expected output:
3 trueBuild minimum counts bottom-up
package main
import ( "fmt")
func minCoins(a int, coins []int) (int, bool) { if a < 0 || a > 10000 { return 0, false } for _, c := range coins { if c <= 0 { return 0, false } } dp := make([]int, a+1) for x := 1; x <= a; x++ { dp[x] = a + 1 for _, c := range coins { if c <= x && dp[x-c]+1 < dp[x] { dp[x] = dp[x-c] + 1 } } } if dp[a] > a { return 0, false } return dp[a], true}func main() { fmt.Println(minCoins(6, []int{4, 3, 1})) fmt.Println(minCoins(5, []int{2, 4})) fmt.Println(minCoins(0, []int{2}))}dp[0]=0; for each amount x, try a final coin c and reuse dp[x-c]. Positive coins make that state earlier. a+1 marks unreachable amounts, since any feasible solution uses at most a positive integer coins. O(a·m) time for m denominations, O(a) memory: pseudo-polynomial in numeric amount, not its bit length. The explicit lab bound prevents huge allocations.
Expected output:
2 true0 false0 trueTry it locally
Implement a DP for ways to climb n steps using 1 or 2 steps, with 0<=n<=30 and ways[0]=1. Print ways for 0 and 5.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 08: Compare greedy and dynamic programming
Check the lesson objective before moving on.
What does the coin example show?
Why must the denominations in the recurrence be positive?