DSA — Greedy Algorithms
What is a Greedy Algorithm?
Makes the locally optimal choice at each stage, hoping to find a global optimum.
Activity Selection Problem
def activity_selection(activities):
activities.sort(key=lambda x: x[1])
selected = [activities[0]]
for i in range(1, len(activities)):
if activities[i][0] >= selected[-1][1]:
selected.append(activities[i])
return selected
Coin Change (Greedy)
def coin_change_greedy(coins, amount):
coins.sort(reverse=True)
count = 0
for coin in coins:
while amount >= coin:
amount -= coin
count += 1
return count
Fractional Knapsack
def fractional_knapsack(weights, values, capacity):
items = sorted(zip(values, weights), key=lambda x: x[0]/x[1], reverse=True)
total = 0
for value, weight in items:
if capacity >= weight:
total += value
capacity -= weight
else:
total += value * (capacity / weight)
break
return total
When Greedy Works
| Problem | Greedy Optimal? |
|---|---|
| Activity Selection | Yes |
| Fractional Knapsack | Yes |
| 0/1 Knapsack | No |
| Huffman Coding | Yes |
Mini Practice
- Solve activity selection
- Implement fractional knapsack
- Create Huffman coding
- Compare with dynamic programming
Up Next
Continue with Backtracking — exploring all possibilities.
Related Topics
Frequently Asked Questions about Greedy Algorithms
What is Greedy Algorithms in DSA?
Greedy Algorithms is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Greedy Algorithms?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Greedy Algorithms.
Why is Greedy Algorithms important in DSA?
Greedy Algorithms is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.