2025-07-07 Daily Challenge

Today I have done leetcode's July LeetCoding Challenge with cpp.

July LeetCoding Challenge 7

Description

Maximum Number of Events That Can Be Attended

You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

You can attend an event i at any day d where startDayi <= d <= endDayi. You can only attend one event at any time d.

Return the maximum number of events you can attend.

 

Example 1:

Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.

Example 2:

Input: events= [[1,2],[2,3],[3,4],[1,2]]
Output: 4

 

Constraints:

  • 1 <= events.length <= 105
  • events[i].length == 2
  • 1 <= startDayi <= endDayi <= 105

Solution

class Solution {
public:
  int maxEvents(vector<vector<int>>& events) {
    int sz = events.size();
    sort(events.begin(), events.end());
    int day = 0;
    int pos = 0;
    int answer = 0;
    priority_queue<int, vector<int>, greater<int>> candidates;
    while(pos < sz || candidates.size()) {
      // cout << day << ' ' << pos << ' ' << answer << endl;
      if(candidates.empty() && pos < sz && events[pos][0] > day) day = events[pos][0];
      while(pos < sz && events[pos][0] <= day) {
        candidates.push(events[pos][1]);
        pos += 1;
      }
      while(candidates.size() && candidates.top() < day) candidates.pop();
      if(candidates.size()) {
        cout << candidates.top() << endl;
        candidates.pop();
        day += 1;
        answer += 1;
      }
    }
    return answer;
  }
};

// Accepted
// 45/45 cases passed (484 ms)
// Your runtime beats 5.01 % of cpp submissions
// Your memory usage beats 30.62 % of cpp submissions (75 MB)