
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program for Activity Selection Problem
The activity selection problem selects the maximum number of non-overlapping activities from a given set. Each activity has a start and finish time, and a single person can perform only one activity at a time.
Problem Statement
You are given n activities, each defined by a start time and a finish time. The goal is to choose the maximum number of activities that a single person can perform without any overlap between the selected activities.
Variable Notations
Below are the variables used in the problem definition:
- N: Total number of activities
- S: An array of start times
- F: An array of finish times
Solving Activity Selection Problem
To solve this problem, we use a greedy strategy where we always pick the next activity that finishes the earliest and does not overlap with the previously selected ones. This approach ensures the maximum number of activities are chosen.
Steps
The greedy solution follows these steps to select non-overlapping activities:
- Sort the activities based on their finish times.
- Select the first activity from the sorted list.
- For the remaining activities, choose an activity if its start time is equal to or greater than the finish time of the last selected activity.
Python Program for Activity Selection Problem
In this example, we first sort the activities based on finish times. We then select the first activity and continue checking subsequent ones to include only non-overlapping ones -
# Function to select maximum number of non-overlapping activities def activity_selection(start, finish): n = len(start) print("The selected activities are:") # First activity is always selected i = 0 print(i, end=" ") # Consider rest of the activities for j in range(1, n): if start[j] >= finish[i]: print(j, end=" ") i = j # Start and finish times start = [1, 2, 0, 3, 2, 4] finish = [2, 5, 4, 6, 8, 8] # Sort activities based on finish time activities = sorted(zip(start, finish), key=lambda x: x[1]) start, finish = zip(*activities) # Run the selection activity_selection(start, finish)
As shown above, the activities at index 0 and 2 are selected as they do not overlap and allow maximum usage of time as shown below -
The selected activities are: 0 2

All the variables are declared in the local scope, and their references are seen in the figure above.