The idea of the solution is that we calculate the sum of the tiles that smaller than the index + carpet length. This is pretty straightforward and intuitive. What if the index + carpet length is larger than the tiles' left index but smaller than its right index? we add it manually.
However, we notice that if we just use a linear search, the Time complexity of our program would be O(n^2) which will cause TLE. Thus, we want to use NlogN to sort the tiles first and then do a binary search on the tiles' ending index.
The only edge case is the index equals 0 and the last index. As we want to check the next tile of the index we found if it contains a part of our answer.
class Solution {
public:
int binarySearch(int target, vector<vector<int>>& end){
int l = 0, r = end.size() - 1,mid;
while(l <= r){
mid=l+(r - l)/2;
if(end[mid][1] > target) r = mid - 1;
else {l = mid + 1;}
}
return l - 1;
}
int maximumWhiteTiles(vector<vector<int>>& tiles, int carpetLen) {
int n = tiles.size();
sort(tiles.begin(), tiles.end());
vector<int> prefix_sum(n, 0);
prefix_sum[0] = tiles[0][1] - tiles[0][0] + 1;
for(int i = 1; i < n; i++)prefix_sum[i] = prefix_sum[i - 1] + (tiles[i][1] - tiles[i][0] + 1);
int ans = 0, part, cur, indx;
for(int i = 0; i < n; i++){
cur = tiles[i][0] + carpetLen - 1;
indx = binarySearch(cur, tiles);
if(indx == -1){
part = cur - tiles[indx + 1][0] + 1;
ans = max(part,ans);
continue;
}
if(i > 0){
part = prefix_sum[indx] - prefix_sum[i - 1];
}else part = prefix_sum[indx];
if(indx < n - 1 && cur >= tiles[indx + 1][0]){
part += cur - tiles[indx + 1][0] + 1;
}
ans = max(ans, part);
}
return ans;
}
};