|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to find the order of meetings that can be scheduled |
| 4 | + // without overlapping, maximizing the number of meetings. |
| 5 | + vector<int> maxMeetings(int n, vector<int> &S, vector<int> &F) { |
| 6 | + vector<int> ans; // To store the result (order of meetings that can be scheduled) |
| 7 | + |
| 8 | + // Vector to store pairs of (start time, end time) with their original index |
| 9 | + vector<pair<pair<int, int>, int>> v; |
| 10 | + |
| 11 | + // Populate the vector with pairs of start and end times along with the meeting index |
| 12 | + for (int i = 0; i < n; i++) { |
| 13 | + v.push_back({{S[i], F[i]}, i + 1}); // Store the start time, end time, and meeting index (1-based) |
| 14 | + } |
| 15 | + |
| 16 | + // Sort the vector of meetings: |
| 17 | + // 1. First by end time (ascending). |
| 18 | + // 2. If two meetings have the same end time, sort by start time (ascending). |
| 19 | + sort(v.begin(), v.end(), [](const pair<pair<int, int>, int>& a, const pair<pair<int, int>, int>& b) { |
| 20 | + if (a.first.second == b.first.second) |
| 21 | + return a.first.first < b.first.first; // Sort by start time if end times are equal |
| 22 | + return a.first.second < b.first.second; // Otherwise, sort by end time |
| 23 | + }); |
| 24 | + |
| 25 | + // Select the first meeting (greedy choice) |
| 26 | + ans.push_back(v[0].second); // Add the index of the first meeting to the result |
| 27 | + int endAns = v[0].first.second; // Store the end time of the first selected meeting |
| 28 | + |
| 29 | + // Iterate through the remaining meetings to find non-overlapping meetings |
| 30 | + for (int i = 1; i < n; i++) { |
| 31 | + // Check if the start time of the current meeting is greater than |
| 32 | + // the end time of the last selected meeting |
| 33 | + if (v[i].first.first > endAns) { |
| 34 | + ans.push_back(v[i].second); // Add the meeting index to the result |
| 35 | + endAns = v[i].first.second; // Update the end time to the current meeting's end time |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + // Sort the result to return the meeting indices in ascending order |
| 40 | + sort(ans.begin(), ans.end()); |
| 41 | + |
| 42 | + return ans; // Return the order of meeting indices that can be scheduled |
| 43 | + } |
| 44 | +}; |
0 commit comments