Could you help me optimize the code, it is exceeding the Time Limit for the test cases, but working fine for custom test cases
Activity selection problem
Hi @drishti307, you can solve this problem in O(n) time complexity by following greedy approach , let me explain
The 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.
So, the algo is simple :-
- Sort the activities according to their finishing time
- 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.
that’s all there is to this problem
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 – {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)).
In case of any doubt feel free to ask
If you got the answer then mark your doubt as resolved
Hi @drishti307, you need to sort according to finishing time
sorting part is tricky if you have’nt done it so refer below code : -
also this question can be solved using bruteforce since n is small (n<=100) so i will suggest u to consider solving this problem with brute force then try above algo that i have mentioned
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.