Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Last active September 5, 2021 20:42
Show Gist options
  • Save ssshukla26/6ec4a4ef5115a101ef9c2434824e85b5 to your computer and use it in GitHub Desktop.
Save ssshukla26/6ec4a4ef5115a101ef9c2434824e85b5 to your computer and use it in GitHub Desktop.
Maximum Number of Events That Can Be Attended [LeetCode 1353]
# Reference : https://www.youtube.com/watch?v=EKZhEN9P2-I
import heapq
class Solution:
def maxEvents(self, events: List[List[int]]) -> int:
# Sort the events in ascending order of their start time
events.sort(key = lambda x: x[0])
# Get max day till the last event is open
max_day = max([event[1] for event in events])
# Init
day = 1
num_events = len(events)
event_idx = 0
event_queue = []
heapq.heapify(event_queue)
event_attended = 0
while day <= max_day:
# Add events which can be attended starting from this day
while event_idx < num_events and events[event_idx][0] <= day:
heapq.heappush(event_queue, events[event_idx][1])
event_idx += 1
# Remove all expried events from the queue
while event_queue and event_queue[0] < day:
heapq.heappop(event_queue)
# pop event if exist
if event_queue:
heapq.heappop(event_queue)
event_attended += 1
# Increment no. of days
day = day + 1
return event_attended
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment