{{announcement.body}}
{{announcement.title}}

# Activity Selection Problem: Algorithms [Code Snippet]

DZone 's Guide to

# Activity Selection Problem: Algorithms [Code Snippet]

### Activity selection problem is a greedy algorithm, i.e always select the next optimal solution.

· Big Data Zone ·
Free Resource

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Activity selection problem is a greedy algorithm, i.e always select the next optimal solution.

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.

If the start time of this activity is greater than the finish time of previously selected activity then select this activity and print it.

## C Implementation:

``````#include<stdio.h>

voidprintMaxActivities(ints[], intf[], intn)
{
inti, j;

printf("Following activities are selected \n");

//first activity always gets selected

i = 0;
printf("%d ", i);
//

for(j = 1; j < n; j++)
{
// If this activity has start time greater than or
// equal to the finish time of previously selected
// activity, then select it
if(s[j] >= f[i])
{
printf("%d ", j);
i = j;
}
}
}

// driver program to test above function
intmain()
{
ints[] =  {1, 3, 0, 5, 8, 5};
intf[] =  {2, 4, 6, 7, 9, 9};
intn = sizeof(s)/sizeof(s[0]);
printMaxActivities(s, f, n);
getchar();
return0;
}
``````

Topics:
algorithms ,code snippet

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.