Greedy Algorithms
Greedy Algorithms
If both of the properties below are true, a greedy algorithm can be used to solve the
problem.
Greedy choice property:
A global (overall) optimal solution can be reached by choosing the optimal choice
at each step.
Optimal substructure:
An optimal solution to the entire problem contains the optimal solutions to the
sub-problems.
SOLUTION.
Step 1: Calculate the value-to-weight ratio
Step 2: Sort treasures by value-to-weight ratio in descending order:
A→B→C
Step 3: Select items:
Take all of Treasure A (10 kg) → Value = ₹60
Take all of Treasure B (20 kg) → Value = ₹100
The remaining capacity is 20 kg.
→ Take 20/30 = 2/3 of Treasure C (20 kg of 30 kg) → Value = 2/3 × ₹120 = ₹80
Result :
Total Weight: 50 kg Total Value: ₹240
Optimal Substructure: A1 1 4
The problem can be broken
into smaller subproblems. A2 3 5
Locally Optimal Choice: Always chooses the option that seems the best at the
moment.
Irrevocability: Once a choice is made, it cannot be changed.
Non-backtracking: Does not reconsider previous decisions.
Efficiency: Generally has a time complexity of O(n) or O(n log n), making it
efficient for some problems.
Not Always Globally Optimal: May not always produce the best overall solution
(global optimum), but works well for specific problems (e.g., fractional knapsack,
activity selection).
Problem-Specific: Works best when the problem exhibits greedy choice
property and optimal substructure.
Steps:
Result:
The left and right edge assignments can follow either
of two conventions:
Convention 1: Left edge = 0, Right edge = 1.
Convention 2: Left edge = 1, Right edge = 0.
Steps:
Initialize distances to all nodes as infinity,
except the source node.
Pick the node with the smallest distance.
Update distances for its neighbors.
Repeat until all nodes are processed.
Typically simpler and faster to implement. May be more complex and slower to implement.
Suitable for problems where local optimization leads to Suitable for problems with overlapping subproblems and
global optimization. optimal substructure.
Minimum Spanning Tree, Shortest Path algorithms. Fibonacci sequence, Longest Common Subsequence.
References:
Introduction to Algorithms, Cormen et al.
Javatpoint.com
Geeksforgeeks.org
Brilliant.org