2274. Maximum Consecutive Floors Without Special Floors Medium

@problem@discussion
#Array#Sorting



1/**
2 * [2274] Maximum Consecutive Floors Without Special Floors
3 *
4 * Alice manages a company and has rented some floors of a building as office space. 
5 * Alice has decided some of these floors should be special floors, used for relaxation only.
6 * You are given two integers bottom and top, which denote that Alice has rented all the 
7 * floors from bottom to top (inclusive). You are also given the integer array special, where
8 * special[i] denotes a special floor that Alice has designated for relaxation.
9 * Return the maximum number of consecutive floors without a special floor.
10 *  
11 * Example 1:
12 * 
13 * Input: bottom = 2, top = 9, special = [4,6]
14 * Output: 3
15 * Explanation: The following are the ranges (inclusive) of consecutive floors without a special floor:
16 * - (2, 3) with a total amount of 2 floors.
17 * - (5, 5) with a total amount of 1 floor.
18 * - (7, 9) with a total amount of 3 floors.
19 * Therefore, we return the maximum number which is 3 floors.
20 * 
21 * Example 2:
22 * 
23 * Input: bottom = 6, top = 8, special = [7,6,8]
24 * Output: 0
25 * Explanation: Every floor rented is a special floor, so we return 0.
26 * 
27 *  
28 * Constraints:
29 * 
30 * 1 <= special.length <= 10^5
31 * 1 <= bottom <= special[i] <= top <= 10^9
32 * All the values of special are unique.
33 * 
34 */
35pub struct Solution {}
36
37// problem: https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/
38// discuss: https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/discuss/?currentPage=1&orderBy=most_votes&query=
39
40// submission codes start here
41
42impl Solution {
43    pub fn max_consecutive(bottom: i32, top: i32, special: Vec<i32>) -> i32 {
44        let mut all = special.clone();
45        all.push(bottom - 1);
46        all.push(top + 1);
47        all.sort();
48
49        let mut max = 0;
50    
51        for i in 0..all.len() - 1 {
52            if all[i + 1] - all[i] - 1 > max {
53                max = all[i + 1] - all[i] - 1;
54            }
55        }
56
57        max
58    }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn test_2274_1() {
69        assert_eq!(Solution::max_consecutive(6, 8, vec![7,6,8]), 0); 
70        assert_eq!(Solution::max_consecutive(2, 9, vec![4,6]), 3); 
71    }
72}
73


Back
© 2025 bowen.ge All Rights Reserved.