We can solve it using dynamic programming by keeping a state that contains the detail about the current index of the activity and the current finish time of the activity so far which we have taken, at each index of the activity we can make 2 decisions either to choose a activity or not, and finally we need to take the maximum of both the choices and recurse.
I have implemented a recursive dp solution in c++ :
#include<bits/stdc++.h>
using namespace std;
int n;
int st[1000], en[1000];
int dp[1000][1000];
int solve(int index, int currentFinishTime){
if(index == n) return 0;
int v1 = 0, v2 = 0;
if(dp[index][currentFinishTime] != -1) return dp[index][currentFinishTime];
//do not choose the current activity
v1 = solve(index+1, currentFinishTime);
//try to choose the current activity
if(st[index] >= currentFinishTime){
v2 = solve(index+1, en[index]) + 1;
}
return dp[index][currentFinishTime] = max(v1, v2);
}
int main(){
cin >> n;
for(int i = 0;i < n;i++) cin >> st[i] >> en[i];
memset(dp, -1, sizeof dp);
cout << solve(0, 0) << endl;
return 0;
}
http://ideone.com/m0mxx2
In this code the dp[index][finish time]
is the dp table used to store the result.