Greedy Algorithm
Greedy Algorithm
Greedy algorithms are a class of algorithms that make locally optimal choices at each stage with the
hope of finding a global optimum. These algorithms are used when the problem has an optimal
substructure and greedy-choice property. In simpler terms, greedy algorithms work by solving a
problem step by step, selecting the best choice available at each step.
total_value = 0
for value, weight, ratio in items:
if capacity >= weight:
capacity -= weight
total_value += value
else:
total_value += ratio * capacity
break
return total_value
def huffman_encoding(data):
if not data:
return "", {}
frequency = defaultdict(int)
for char in data:
frequency[char] += 1
huffman_tree = heap[0]
return ''.join([pair[1] for pair in huffman_tree[1:]]), {pair[0]: pair[1]
for pair in huffman_tree[1:]}
selected_activities = [activities[0]]
last_finish_time = activities[0][1]
Disadvantages:
• Non-optimal Solutions: Greedy algorithms do not always produce the optimal solution,
especially in problems where optimal substructure does not hold.
• Limited Application: Not all problems can be solved optimally with greedy algorithms.
6. Conclusion
Greedy algorithms are powerful and efficient in solving certain types of problems, especially those
with optimal substructure and greedy-choice properties. However, their applicability is limited, and
they do not always guarantee the best solution. Understanding when and where to use greedy
algorithms is crucial in algorithm design and problem-solving.