0
0
DSA Cprogramming~3 mins

Greedy vs DP How to Know Which to Apply in DSA C - Why the Distinction Matters

Choose your learning style9 modes available
The Big Idea

Can picking the obvious best choice every time actually lead you astray?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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;
}
After
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;
  }
}
What It Enables

These methods let you solve complex choice problems quickly and correctly, saving time and avoiding mistakes.

Real Life Example

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.

Key Takeaways

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.