Maximum Consecutive Floors Without Special Floors - Problem

Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.

You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation.

Return the maximum number of consecutive floors without a special floor.

Input & Output

Example 1 — Basic Case
$ Input: bottom = 2, top = 9, special = [4,6]
Output: 3
💡 Note: The floors are 2,3,4,5,6,7,8,9 where 4 and 6 are special. The gaps are: floors 2-3 (2 consecutive), floors 5 (1 consecutive), floors 7-8-9 (3 consecutive). Maximum is 3.
Example 2 — No Special Floors
$ Input: bottom = 6, top = 8, special = []
Output: 3
💡 Note: No special floors exist, so all floors 6,7,8 are consecutive regular floors. Answer is 3.
Example 3 — All Special
$ Input: bottom = 1, top = 3, special = [1,2,3]
Output: 0
💡 Note: All floors are special, so there are 0 consecutive regular floors.

Constraints

  • 1 ≤ special.length ≤ 105
  • 1 ≤ bottom ≤ special[i] ≤ top ≤ 109
  • All the values of special are unique.

Visualization

Tap to expand
Maximum Consecutive Floors Without Special Floors INPUT 9 8 7 6 SPECIAL 5 4 SPECIAL 3 2 bottom = 2 top = 9 special = [4, 6] Normal Special ALGORITHM STEPS 1 Sort Special [4, 6] already sorted 2 Check Start Gap special[0] - bottom 4 - 2 = 2 floors 3 Check Middle Gaps Between consecutive specials 6 - 4 - 1 = 1 floor 4 Check End Gap top - special[last] 9 - 6 = 3 floors Gaps found: [2, 1, 3] --> max = 3 FINAL RESULT 9 8 7 6 5 4 3 2 3 OUTPUT 3 Max consecutive floors Key Insight: Sort special floors, then find maximum gap among three regions: (1) Before first special, (2) Between consecutive specials, (3) After last special. Time: O(n log n) for sorting | Space: O(1) extra TutorialsPoint - Maximum Consecutive Floors Without Special Floors | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen