activity selection Algorithm

The activity selection algorithm is a powerful and efficient method used in solving optimization problems where a set of tasks, or activities, need to be scheduled under specific constraints. The goal of the algorithm is to select the maximum number of non-overlapping activities that can be completed within a given timeframe. This type of problem can be found in various real-life scenarios, such as scheduling events in a conference or assigning tasks to machines in a factory. The algorithm typically employs a greedy strategy, meaning it makes the best possible choice at each step, in hopes of finding the overall optimal solution. One of the most famous activity selection algorithms is the greedy algorithm, which operates by sorting the activities based on their finish times in ascending order. The algorithm then initializes an empty set to store the selected activities and chooses the first activity with the earliest finish time. After the initial selection, the algorithm iterates through the remaining activities and only selects those which start after the previously selected activity has finished. By always selecting the activity with the earliest finish time, the algorithm ensures that the maximum number of non-overlapping activities can be completed within the given timeframe. This greedy strategy not only guarantees an optimal solution, but also has a relatively low time complexity, making it an ideal choice for solving large-scale problems.
# flake8: noqa

"""The following implementation assumes that the activities
are already sorted according to their finish time"""

"""Prints a maximum set of activities that can be done by a
single person, one at a time"""
# n --> Total number of activities
# start[]--> An array that contains start time of all activities
# finish[] --> An array that contains finish time of all activities


def printMaxActivities(start, finish):
    """
    >>> start = [1, 3, 0, 5, 8, 5]
    >>> finish = [2, 4, 6, 7, 9, 9]
    >>> printMaxActivities(start, finish)
    The following activities are selected:
    0 1 3 4 
    """
    n = len(finish)
    print("The following activities are selected:")

    # The first activity is always selected
    i = 0
    print(i, end=" ")

    # Consider rest of the activities
    for j in range(n):

        # If this activity has start time greater than
        # or equal to the finish time of previously
        # selected activity, then select it
        if start[j] >= finish[i]:
            print(j, end=" ")
            i = j


# Driver program to test above function
start = [1, 3, 0, 5, 8, 5]
finish = [2, 4, 6, 7, 9, 9]
printMaxActivities(start, finish)

"""
The following activities are selected:
0 1 3 4
"""

LANGUAGE:

DARK MODE: