Following is the problem statement:

Example 1 :Consider the following 3 activities sorted by finish time. StartTime[] = {10, 12, 20}; FinishTime[] = {20, 25, 30}; Maximum number of tasks performed by person is2.Maximum set of activities that can be executed is {0, 2} [ These are indexes in StartTmie[] and FinishTime[] ]Example 2 :Consider the following 6 activities sorted by by finish time. startTime[] = {1, 3, 0, 5, 8, 5}; finishTime[] = {2, 4, 6, 7, 9, 9}; A person can perform at mostfouractivities. The maximum set of activities that can be executed is {0, 1, 3, 4} [ These are indexes in startTime[] and finishTime[] ]

The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of previously selected activity. We can sort the activities according to their finishing time so that we always consider the next activity as minimum finishing time activity.1) Sort the activities according to their finishing time

2) Select the first activity from the sorted array and print it.

3) Do following for remaining activities in the sorted array.-------.a) If the start time of this activity is greater than or equal to the finish time of previously selected activity then select this activity and print it.How does Greedy Choice work for Activities sorted according to finish time?

Let the given set of activities be S = {1, 2, 3, ..n} and activities be sorted by finish time. The greedy choice is to always pick activity 1. How come the activity 1 always provides one of the optimal solutions. We can prove it by showing that if there is another solution B with the first activity other than 1, then there is also a solution A of the same size with activity 1 as the first activity. Let the first activity selected by B be k, then there always exist A = {B %u2013 {k}} U {1}.(Note that the activities in B are independent and k has smallest finishing time among all. Since k is not 1, finish(k) >= finish(1))#include <bits/stdc++.h>using namespace std;struct activity{int start, finish;};bool Compare(activity s1, activity s2){return (s1.finish < s2.finish);}void print(activity vec[], int n){sort(vec, vec+n, Compare);cout << "Following activities are selected - ";int i = 0;cout << "(" << vec[i].start << ", " << vec[i].finish << "), ";for (int j = 1; j < n; j++){if (vec[j].start >=vec[i].finish){cout << "(" << vec[j].start << ", "<< vec[j].finish << "), ";i = j;}}}int main(){activity vec[] = {{4, 8}, {2, 5}, {4, 6}, {1, 4},{3, 7}, {8, 9}};int n = sizeof(vec)/sizeof(vec[0]);print(vec, n);return 0;}Output:Following activities are selected - (1,4), (4,6), (8,9)

## Comments