Skip to content

Commit 2364494

Browse files
committed
Add activity selection new algorithm
1 parent a9ca110 commit 2364494

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
The Activity Selection Problem is a classic problem in which a set of activities,
3+
each with a start and end time, needs to be scheduled in such a way that
4+
the maximum number of non-overlapping activities is selected.
5+
This is a greedy algorithm where at each step,
6+
we choose the activity that finishes the earliest
7+
and does not conflict with previously selected activities.
8+
9+
Wikipedia: https://en.wikipedia.org/wiki/Activity_selection_problem
10+
"""
11+
12+
13+
def activity_selection(activities: list[tuple[int, int]]) -> list[tuple[int, int]]:
14+
"""
15+
Solve the Activity Selection Problem using a greedy algorithm by selecting
16+
the maximum number of non-overlapping activities from a list of activities.
17+
18+
Parameters:
19+
activities: A list of tuples where each tuple contains
20+
the start and end times of an activity.
21+
22+
Returns:
23+
A list of selected activities that are non-overlapping.
24+
25+
Example:
26+
>>> activity_selection([(1, 3), (2, 5), (3, 9), (6, 8)])
27+
[(1, 3), (6, 8)]
28+
29+
>>> activity_selection([(0, 6), (1, 4), (3, 5), (5, 7), (5, 9), (8, 9)])
30+
[(1, 4), (5, 7), (8, 9)]
31+
32+
>>> activity_selection([(1, 2), (2, 4), (3, 5), (0, 6)])
33+
[(1, 2), (2, 4)]
34+
35+
>>> activity_selection([(5, 9), (1, 2), (3, 4), (0, 6)])
36+
[(1, 2), (3, 4), (5, 9)]
37+
"""
38+
39+
# Step 1: Sort the activities by their end time
40+
sorted_activities = sorted(activities, key=lambda x: x[1])
41+
42+
# Step 2: Select the first activity (the one that finishes the earliest)
43+
# as the initial activity
44+
selected_activities = [sorted_activities[0]]
45+
46+
# Step 3: Iterate through the sorted activities and select the ones
47+
# that do not overlap with the last selected activity
48+
for i in range(1, len(sorted_activities)):
49+
if sorted_activities[i][0] >= selected_activities[-1][1]:
50+
selected_activities.append(sorted_activities[i])
51+
52+
return selected_activities

0 commit comments

Comments
 (0)