Similar Problems

Similar Problems not available

Maximum Consecutive Floors Without Special Floors - Leetcode Solution

Companies:

LeetCode:  Maximum Consecutive Floors Without Special Floors Leetcode Solution

Difficulty: Medium

Topics: sorting array  

Problem Statement: You are installing a new elevator in a building with n floors. The elevator has m special floors, where it stops at each. There are multiple elevators in the building, and each elevator can only stop at up to k consecutive floors without stopping at a special floor. You need to determine the maximum number of consecutive floors that an elevator can serve without stopping at a special floor.

Solution: The problem can be solved using a sliding window approach. We can start by sorting the special floors in increasing order so that we can calculate the maximum number of consecutive floors an elevator can serve without stopping at a special floor. We can start with the first elevator at the first floor and the end of the window at the kth floor.

We can keep moving the window towards the end of the building, checking if we have passed any special floors. If we have crossed a special floor, we can reset the window to the current floor and start again. If we have not crossed any special floors, we can move the end of the window to the next floor.

We can repeat this process until we reach the top floor, keeping track of the maximum consecutive floors served by the elevator. We can then move on to the next elevator and repeat the process.

The time complexity of this approach is O(m log m + nm) where m is the number of special floors and n is the number of elevators. The space complexity is O(m).

Code:

class Solution {
public:
    int maxConsecutiveFloors(int n, int m, int k, vector<int>& special) {
        sort(special.begin(), special.end());
        int ans = 0;
        for(int i = 0; i < n; i += k) {
            int s = i, e = min(i + k - 1, n - 1);
            auto it = upper_bound(special.begin(), special.end(), e);
            if(it != special.begin() && *(--it) >= s) {
                // Found a special floor within the window
                e = *it - 1;
            }
            ans = max(ans, e - s + 1);
        }
        return ans;
    }
};

We can call the above function maxConsecutiveFloors to find the maximum number of consecutive floors an elevator can serve without stopping at a special floor. The function takes in the total number of floors n, the number of special floors m, the maximum number of consecutive floors that can be served without stopping at a special floor k, and the vector special containing the positions of the special floors. The function returns the maximum number of consecutive floors served by an elevator.

Maximum Consecutive Floors Without Special Floors Solution Code

1