Which condition best indicates that a greedy algorithm is the right choice instead of dynamic programming?
Think about when making the best local choice leads to a global best solution.
Greedy algorithms work when the problem has the greedy choice property, meaning a local optimal choice leads to a global optimum. Dynamic programming is needed when overlapping subproblems exist but greedy choice property does not hold.
What is the output of the following C# code that uses a greedy approach to make change?
int[] coins = {25, 10, 5, 1}; int amount = 37; List<int> result = new List<int>(); foreach (int coin in coins) { while (amount >= coin) { amount -= coin; result.Add(coin); } } Console.WriteLine(string.Join(",", result));
Count how many coins are needed to sum up to 37 using the largest coins first.
The greedy algorithm picks 25 once, then 10 once, then two 1-cent coins to make 37 cents total.
Consider the following code that tries to find the minimum number of coins for amount 6 using coins {1,3,4} greedily. What is the output and why is it incorrect?
int[] coins = {4, 3, 1}; int amount = 6; List<int> result = new List<int>(); foreach (int coin in coins) { while (amount >= coin) { amount -= coin; result.Add(coin); } } Console.WriteLine(string.Join(",", result));
Check how the greedy picks coins and if it finds the minimum number.
The greedy picks 4 first, then two 1s, totaling 3 coins. But the optimal solution is two 3s (2 coins). Greedy fails because the greedy choice property does not hold here.
Given the following C# code for the classic Fibonacci sequence using dynamic programming, what is the value of dp[5] after execution?
int n = 7; int[] dp = new int[n+1]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) { dp[i] = dp[i-1] + dp[i-2]; } Console.WriteLine(dp[5]);
Recall Fibonacci sequence: 0,1,1,2,3,5,8,13...
dp[5] corresponds to the 5th Fibonacci number which is 5.
Which of the following problem characteristics best indicates that dynamic programming is needed instead of a greedy approach?
Think about when you must remember results of subproblems to avoid repeated work.
Dynamic programming is used when the problem has overlapping subproblems and optimal substructure but does not satisfy the greedy choice property, so greedy algorithms fail.
