Can picking the obvious best choice every time actually lead you astray?
Greedy vs DP How to Know Which to Apply in DSA C - Why the Distinction Matters
Imagine you have a big jar of coins and you want to pick coins to make a certain amount of money. You try to pick the biggest coin first every time, hoping it will add up quickly.
Picking the biggest coin first might seem smart, but sometimes it leads you to miss the best combination. You might end up with more coins or fail to reach the exact amount. Doing this by hand is slow and confusing.
Greedy and Dynamic Programming (DP) are smart ways to solve such problems. Greedy picks the best choice at each step quickly, but DP looks at all choices and remembers past results to find the best overall answer.
int amount = 11; int coins[] = {5, 3, 1}; // Pick biggest coin first every time while(amount > 0) { if(amount >= 5) amount -= 5; else if(amount >= 3) amount -= 3; else amount -= 1; }
int amount = 11; int coins[] = {5, 3, 1}; int dp[12] = {0}; for(int i = 1; i <= amount; i++) { dp[i] = 1000; for(int j = 0; j < 3; j++) { if(coins[j] <= i && dp[i - coins[j]] + 1 < dp[i]) dp[i] = dp[i - coins[j]] + 1; } }
These methods let you solve complex choice problems quickly and correctly, saving time and avoiding mistakes.
Choosing the best route on a map: Greedy might pick the shortest road at each turn, but DP considers all routes to find the fastest overall path.
Greedy is fast but only works when local best choices lead to global best.
DP checks all possibilities and remembers results to find the best overall solution.
Knowing when to use each saves time and gets correct answers.