#2274
Maximum Consecutive Floors Without Special Floors
MediumArraySortingSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n log n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the special floors and calculating gaps between them, we can efficiently find the maximum number of consecutive non-special floors. This avoids unnecessary checks for every floor.
⚙️
Algorithm
5 steps- 1Step 1: Sort the special array.
- 2Step 2: Initialize max_count with the gap before the first special floor and after the last special floor.
- 3Step 3: Iterate through the sorted special floors, calculating the gaps between consecutive special floors.
- 4Step 4: Update max_count with the maximum gap found.
- 5Step 5: Return max_count.
solution.py7 lines
1def maxConsecutive(bottom, top, special):
2 special.sort()
3 max_count = special[0] - bottom
4 for i in range(1, len(special)):
5 max_count = max(max_count, special[i] - special[i - 1] - 1)
6 max_count = max(max_count, top - special[-1])
7 return max_countℹ
Complexity note: The time complexity is O(n log n) due to sorting the special floors. The space complexity is O(1) as we only use a few variables for counting.
- 1Sorting helps in efficiently calculating gaps between special floors.
- 2The maximum gap can occur before the first special floor or after the last special floor.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.