Skip to content

Commit d3266d7

Browse files
authored
Create main.cpp
1 parent 91d93f2 commit d3266d7

File tree

1 file changed

+36
-0
lines changed
  • 25 - Greedy Algorithm Problems/10 - Activity Selection

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
// Function to find the maximum number of activities that can be selected
4+
int activitySelection(vector<int> &start, vector<int> &end) {
5+
int n = start.size(); // Get the number of activities
6+
7+
// Step 1: Create a vector of pairs to store the start and end times of each activity
8+
vector<pair<int, int>> v;
9+
10+
// Step 2: Fill the vector 'v' with pairs of (start time, end time)
11+
for(int i = 0; i < n; i++){
12+
v.push_back({start[i], end[i]});
13+
}
14+
15+
// Step 3: Sort the activities based on their end time (ascending order)
16+
sort(v.begin(), v.end(), [](pair<int, int> a, pair<int, int> b){
17+
return a.second < b.second; // Sort by the end time of the activity
18+
});
19+
20+
// Step 4: Initialize variables
21+
int activityCount = 1; // The first activity is always selected
22+
int endTime = v[0].second; // Set the end time of the first activity
23+
24+
// Step 5: Loop through the remaining activities and select those that do not overlap
25+
for(int i = 1; i < n; i++){
26+
// If the start time of the current activity is greater than the end time of the last selected activity
27+
if(v[i].first > endTime){
28+
activityCount++; // Select the activity
29+
endTime = v[i].second; // Update the end time to the end time of the current activity
30+
}
31+
}
32+
33+
// Step 6: Return the total number of activities selected
34+
return activityCount;
35+
}
36+
};

0 commit comments

Comments
 (0)