DEV Community

codingpineapple
codingpineapple

Posted on

2 2

LeetCode 1353. Maximum Number of Events That Can Be Attended (javascript solution)

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;
};
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay