LeetCode 1353. Maximum Number of Events That Can Be Attended (javascript solution)
codingpineapple
Posted on May 24, 2021
Description:
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.
Solution:
Time Complexity : O(n^2)
Space Complexity: O(n)
var maxEvents = function(events) {
let visited = {};
// Sort events: endTime smaller to bigger, if endTimes are same, prioritize startTime smaller one
events = events.sort((a,b)=>{
if(a[1]!=b[1]) return a[1] - b[1];
return a[0] - b[0];
});
let res=0;
// Loop through the events and increment the number of days we can attend a unique event
for(let k=0;k<events.length;k++) {
let event = events[k];
let start = event[0];
let end = event[1];
for(let i=start;i<=end;i++) {
// Only count a day as visited if it has an event we have not visited yet
if(!visited[i]) {
visited[i] = true;
res++;
break;
}
}
}
return res;
};
π πͺ π
π©
codingpineapple
Posted on May 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
sorting Recap the highlight of the sorting algorithms using JavaScript for beginners
October 5, 2024
datastructures DSA with JS: Understanding Custom Array Data Structure in JavaScript - A Step-by-Step Guide
September 29, 2024