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 themaximum number of consecutive floors without a special floor.
Input: bottom =2, top =9, special =[4,6]Output: 3Explanation: The following are the ranges(inclusive) of consecutive floors without a special floor:-(2,3)with a total amount of 2 floors.-(5,5)with a total amount of 1 floor.-(7,9)with a total amount of 3 floors.Therefore, we return the maximum number which is3 floors.
The main idea is to find the largest gap between consecutive special floors (including the edges: bottom and top). By sorting the special floors, we can easily compute the maximum number of consecutive non-special floors between them.
classSolution {
public:int maxConsecutive(int bottom, int top, vector<int>& special) {
sort(special.begin(), special.end());
int ans =0;
ans = max(ans, special[0] - bottom);
for (int i =1; i < special.size(); ++i) {
ans = max(ans, special[i] - special[i-1] -1);
}
ans = max(ans, top - special.back());
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcmaxConsecutive(bottomint, topint, special []int) int {
sort.Ints(special)
ans:=special[0] -bottomfori:=1; i < len(special); i++ {
ifspecial[i]-special[i-1]-1 > ans {
ans = special[i] -special[i-1] -1 }
}
iftop-special[len(special)-1] > ans {
ans = top-special[len(special)-1]
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintmaxConsecutive(int bottom, int top, int[] special) {
Arrays.sort(special);
int ans = special[0]- bottom;
for (int i = 1; i < special.length; i++) {
ans = Math.max(ans, special[i]- special[i-1]- 1);
}
ans = Math.max(ans, top - special[special.length-1]);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaxConsecutive(bottom: Int, top: Int, special: IntArray): Int {
special.sort()
var ans = special[0] - bottom
for (i in1 until special.size) {
ans = maxOf(ans, special[i] - special[i-1] - 1)
}
ans = maxOf(ans, top - special.last())
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxConsecutive(self, bottom: int, top: int, special: list[int]) -> int:
special.sort()
ans = special[0] - bottom
for i in range(1, len(special)):
ans = max(ans, special[i] - special[i-1] -1)
ans = max(ans, top - special[-1])
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnmax_consecutive(bottom: i32, top: i32, mut special: Vec<i32>) -> i32 {
special.sort_unstable();
letmut ans = special[0] - bottom;
for i in1..special.len() {
ans = ans.max(special[i] - special[i-1] -1);
}
ans = ans.max(top - special[special.len()-1]);
ans
}
}