Welcome to a fascinating journey into the world of Greedy Algorithms! This lesson is designed to help both beginners and intermediate learners understand and apply this powerful technique in their coding projects. š
Greedy algorithms are a type of problem-solving approach used in computer science to find an approximate solution to optimization problems. They work by making the locally optimal choice at each stage with the hope that this choice will lead to a global optimum.
Let's dive into two examples to better understand the concept.
Given a list of activities with their start and end times, choose the maximum number of activities that don't overlap.
activities = [(1, 4), (2, 3), (0, 1), (2, 5), (3, 4), (0, 2), (6, 8)]
activities.sort(key=lambda x: x[1]) # Sort by end time
selected_activities = []
current_end = -1
for activity in activities:
start, end = activity
if start >= current_end:
selected_activities.append(activity)
current_end = end
print(len(selected_activities)) # Output: 4In this example, we first sort the activities by their end times. At each step, we consider the next activity and check if its start time is greater than or equal to the current end time of the previously selected activity. If so, we add the new activity to our selection and update the current end time.
Given a set of items with weights and values, find the items to include in a knapsack of limited capacity to maximize total value.
items = [(3, 4), (1, 2), (6, 5), (5, 6)]
capacity = 9
items.sort(key=lambda x: x[1]/x[0], reverse=True) # Sort by value/weight ratio
knapsack = []
current_weight = 0
for item in items:
weight, value = item
if current_weight + weight <= capacity:
knapsack.append(item)
current_weight += weight
print(sum([item[1] for item in knapsack])) # Output: 13In this example, we first sort the items by their value-to-weight ratio. At each step, we consider the next item and check if adding it won't exceed the current knapsack capacity. If not, we add the item to our selection and update the current weight.
In the Activity Selection Problem, the sorting is done by what parameter?
With these examples, we hope you now have a better understanding of what greedy algorithms are and how they can be used in practice. Happy coding! š”šÆ