|
| 1 | +# Problem Name: Activity Selection Problem |
| 2 | +# Method used: Greedy Approach |
| 3 | + |
| 4 | +# ------------------------------------------------------------------------- |
| 5 | + |
| 6 | +# Problem Statement: You are given n activities with their start and finish times. |
| 7 | +# Select the maximum number of activities that can be performed |
| 8 | +# by a single person, assuming that a person can only work on a |
| 9 | +# single activity at a time. |
| 10 | + |
| 11 | +# ------------------------------------------------------------------------- |
| 12 | + |
| 13 | +# Constraints: |
| 14 | +# n --> Total number of activities |
| 15 | +# s[]--> An array that contains start time of all activities |
| 16 | +# f[] --> An array that contains finish time of all activities |
| 17 | + |
| 18 | + |
| 19 | +# Let's solve the problem. |
| 20 | + |
| 21 | +# This is the actual function, which is going to find out the result for this problem. |
| 22 | +# The function printMaxActivities takes two parameters, s and f |
| 23 | +# s[] denotes all the start time activities. |
| 24 | +# f[] denotes all the finish time activities. |
| 25 | +def printMaxActivities(s, f ): |
| 26 | + n = len(f) |
| 27 | + print ("The following activities are selected") |
| 28 | + |
| 29 | + # The first activity is always selected |
| 30 | + i = 0 |
| 31 | + print (i,end=' ') |
| 32 | + |
| 33 | + # Consider rest of the activities |
| 34 | + for j in range(1, n): |
| 35 | + |
| 36 | + # If this activity has start time greater than |
| 37 | + # or equal to the finish time of previously |
| 38 | + # selected activity, then select it |
| 39 | + if s[j] >= f[i]: |
| 40 | + print (j,end=' ') |
| 41 | + i = j |
| 42 | + |
| 43 | +# Driver program to test above function |
| 44 | +print ("-- Activity Selection Problem using Greedy Approach --\n") |
| 45 | +s = [1 , 3 , 0 , 5 , 8 , 5] |
| 46 | +f = [2 , 4 , 6 , 7 , 9 , 9] |
| 47 | +print ("** Activities during start time **") |
| 48 | +print (s) |
| 49 | +print ("** Activities during finish time **") |
| 50 | +print (f) |
| 51 | +print () |
| 52 | +printMaxActivities(s , f) |
| 53 | + |
| 54 | + |
| 55 | +# ------------------------------------------------------------------------- |
| 56 | + |
| 57 | +# Output: |
| 58 | +# -- Activity Selection Problem using Greedy Approach -- |
| 59 | + |
| 60 | +# ** Activities during start time ** |
| 61 | +# [1, 3, 0, 5, 8, 5] |
| 62 | +# ** Activities during finish time ** |
| 63 | +# [2, 4, 6, 7, 9, 9] |
| 64 | + |
| 65 | +# The following activities are selected |
| 66 | +# 0 1 3 4 |
| 67 | + |
| 68 | +# ------------------------------------------------------------------------- |
| 69 | + |
| 70 | +# Code contributed by, Abhishek Sharma, 2022 |
| 71 | + |
| 72 | +# ------------------------------------------------------------------------- |
0 commit comments