Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2274. Maximum Consecutive Floors Without Special Floors

ArraySorting

Explanation

To solve this problem, we can iterate through each special floor and find the maximum gap between them. The maximum gap can occur at the beginning before the first special floor, in between two special floors, or at the end after the last special floor. We can calculate these gaps and return the maximum gap as the result.

  • Sort the special floors array.
  • Initialize maxGap to be the maximum of the first special floor index and the difference between the first special floor and the bottom floor.
  • Iterate through the special floors array and calculate the gap between consecutive special floors.
  • Update maxGap with the maximum of the current gap and the difference between the current special floor and the previous special floor.
  • Calculate the gap between the last special floor and the top floor.
  • Update maxGap with the maximum of the last gap and the difference between the top floor and the last special floor.
class Solution {
    public int maxConsecutiveFloors(int bottom, int top, int[] special) {
        Arrays.sort(special);
        int maxGap = Math.max(special[0] - bottom, 0);
        
        for (int i = 1; i < special.length; i++) {
            int gap = special[i] - special[i - 1] - 1;
            maxGap = Math.max(maxGap, gap);
        }
        
        maxGap = Math.max(maxGap, top - special[special.length - 1]);
        
        return maxGap;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.