Greedy Algorithms
Greedy Algorithms - Theory
Introduction
Greedy algorithms are a paradigm for solving optimization problems. The main idea behind a greedy algorithm is to make a sequence of choices, each of which looks the best at the moment. It chooses the optimal solution at every step with the hope that these local optimal choices will lead to a global optimal solution.
Unlike dynamic programming, where you solve every subproblem and then combine the solutions to form the optimal solution for the entire problem, greedy algorithms directly pick what seems to be the best option at each decision point.
Video Explanation

Beginner-Friendly Explanation
A Greedy Algorithm solves a problem step by step.
At every step, it chooses the option that looks best at that moment.
The main goal is to find an optimal solution quickly by making local best choices.
Real-Life Example
Imagine you have limited money and want to buy the maximum number of chocolates.
A greedy approach would pick the cheapest chocolate first, then the next cheapest, and so on.
This strategy tries to maximize the total number of chocolates you can buy.
Characteristics of Greedy Algorithms
-
Greedy Choice Property: A globally optimal solution can be arrived at by making locally optimal choices. The algorithm assumes that by choosing the optimal solution at each step, the overall solution will be optimal.
-
Optimal Substructure: A problem has an optimal substructure if an optimal solution to the problem can be constructed efficiently from optimal solutions of its subproblems. This is necessary for a greedy algorithm to be valid.
-
Non-Overlapping Subproblems: Greedy algorithms generally work well when subproblems don’t overlap (like in dynamic programming), which allows making decisions based only on local information.
How Greedy Algorithms Work
- Step 1: Greedy Choice: At each step, choose the best possible option available. This is a local optimization.
- Step 2: Reduce Problem Size: After making the choice, reduce the problem size. The remaining subproblem must also satisfy the properties of the greedy approach.
- Step 3: Repeat: Repeat the greedy choice step until the problem is reduced to a simple base case.
Applications of Greedy Algorithms
Greedy algorithms are applied to a variety of problems, especially in optimization scenarios:
- Activity Selection Problem: Selecting the maximum number of activities that don't overlap.
- Huffman Coding: A compression algorithm used for lossless data compression.
- Kruskal's and Prim's Algorithm: Used to find the Minimum Spanning Tree (MST) in a graph.
- Dijkstra's Algorithm: Used to find the shortest path from one source to all other vertices in a graph.
Dry Run Example
Problem:
Select the maximum number of non-overlapping activities.
| Activity | Start Time | End Time |
|---|---|---|
| A | 1 | 3 |
| B | 2 | 5 |
| C | 4 | 6 |
| D | 6 | 8 |