LeetCode 2534: Time Taken to Cross the Door

Problem Description

Explanation:

To solve this problem, we can use a priority queue to keep track of the time taken for each person to cross the door. We will iterate through the given array of times and simulate the process of people crossing the door.

For each person, we will check if there is space for them to cross immediately. If there is space, we update the current time to be the maximum of the current time and the person's arrival time. If there is no space, we add the person's crossing time to the current time and update the total time taken to cross the door.

After iterating through all the people, the total time taken to cross the door will be the maximum of the current time and the last person's arrival time.

Algorithm:

  1. Sort the given array of times in ascending order.
  2. Initialize a priority queue to store the times taken for each person to cross the door.
  3. Initialize a variable currentTime to keep track of the current time.
  4. Iterate through the sorted array of times:
    • If there is space for the current person to cross immediately, update the currentTime to be the maximum of the current time and the person's arrival time.
    • If there is no space, add the person's crossing time to the currentTime and update the total time taken to cross the door.
  5. Return the maximum of the currentTime and the last person's arrival time as the total time taken to cross the door.

Time Complexity: O(n log n) - Sorting the array of times takes O(n log n) time, where n is the number of people. Space Complexity: O(n) - Using a priority queue to store the times taken for each person.

:

Solutions

import java.util.Arrays;
import java.util.PriorityQueue;

class Solution {
    public int timeTakenToCrossDoor(int[] times) {
        Arrays.sort(times);
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        int currentTime = 0;
        
        for (int time : times) {
            if (!pq.isEmpty() && pq.peek() <= currentTime) {
                pq.poll();
            } else {
                currentTime = time;
            }
            pq.offer(time + 3);
        }
        
        return Math.max(currentTime, pq.peek());
    }
}

Loading editor...