# 14.Maximum Number of Events That Can Be Attended

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 `startTimei <= d <= endTimei`. Notice that you can only attend one event at any time `d`.

Return *the maximum number of events* you can attend.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/02/05/e1.png)

```
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
```

**Example 3:**

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

**Example 4:**

```
Input: events = [[1,100000]]
Output: 1
```

**Example 5:**

```
Input: events = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7]]
Output: 7
```

## Solution: (Greedy)

Everyday we visit fastest ending event.

```cpp
class Solution
{
public:
    int maxEvents(vector<vector<int>> &events)
    {

        sort(events.begin(), events.end());

        priority_queue<int, vector<int>, greater<int>> pq;

        int res = 0;
        int j = 0, i = 1;
        int n = events.size();

        while (i <= 100000)
        {

            while (!pq.empty() && pq.top() < i)
            {
                pq.pop();
            }

            while (j < n && events[j][0] == i)
            {
                pq.push(events[j][1]);
                j++;
            }

            if (!pq.empty())
            {
                pq.pop();
                res++;
            }

            i++;
        }

        return res;
    }
};
```

**Time Complexity: O(n log n)**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/greedy-algorithms/14.maximum-number-of-events-that-can-be-attended.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
