# C Program for Activity Selection Problem

The activity selection problem is a problem in which we are given a set of activities with their starting and finishing times. And we need to find all those activities that a person can do performing the single activity at a time.

The greedy algorithm is appointed in this problem to select the next activity that is to be performed. Let’s first understand the greedy algorithm.

Greedy Algorithm is an algorithm that tries to find the solution to a problem by finding the solution step by step. For selecting the next step, the algorithm also selected the step that seems to be the most promising i.e. can lead to the optimised solution immediately as compared to rest. The greedy algorithm is used to solve optimization problems as it tries to find the most optimized solution for the next intermediate step that leads to an optimal solution to the whole problem.

Though the greedy algorithm is a good solution but there are some problems with which it cannot be applied. For example, 0-1 knapsack cannot be solved using the greedy algorithm.

## Algorithm

Some standard greedy algorithm is −

1) Dijkstrata’s Shortest Path
2) Minimum Spanning Tree (MST) {prim’s and kruskal’s}
3) Huffman coding

Inactivity selection problem, we are given n problems with starting and finishing time. And we need to select the maximum number of activities that can be performed by an individual is given that he can do a single activity at a point of time.

There are 3 activities which are sorted in order of their finishing time,

Start = [1 , 5 , 12 ]
End = [10, 13, 23]

Here, the person will be able to perform two activities at most. Activities that can be executed are [0, 2].

## Example

Live Demo

#include<stdio.h>
int main(){
int start[] = {1 , 5 , 12};
int finish[] = {10, 13, 23};
int activities = sizeof(start)/sizeof(start[0]);
int i, j;
printf ("Following activities are selected \t");
i = 0;
printf("%d\t", i);
for (j = 1; j < activities; j++){
if (start[j] >= finish[i]){
printf ("%d ", j);
i = j;
}
}
return 0;
}

## Output

Following activities are selected 0 2

Updated on: 03-Jan-2020

4K+ Views