Maximum White Tiles Covered by a Carpet Problem
Description
LeetCode Problem 2271.
You are given a 2D integer array tiles where tiles[i] = [l_i, r_i] represents that every tile j in the range l_i <= j <= r_i is colored white.
You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.
Return the maximum number of white tiles that can be covered by the carpet.
Example 1:

Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10
Output: 9
Explanation: Place the carpet starting on tile 10.
It covers 9 white tiles, so we return 9.
Note that there may be other places where the carpet covers 9 white tiles.
It can be shown that the carpet cannot cover more than 9 white tiles.
Example 2:

Input: tiles = [[10,11],[1,1]], carpetLen = 2
Output: 2
Explanation: Place the carpet starting on tile 10.
It covers 2 white tiles, so we return 2.
Constraints:
1 <= tiles.length <= 5 * 10^4tiles[i].length == 21 <= l_i <= r_i <= 10^91 <= carpetLen <= 10^9- The
tilesare non-overlapping.
Solution
Approach: Sorting + Sliding Window
Sort the tiles by start. It is always best to start the carpet at the left end of some interval. For each starting interval i, advance a pointer j over the intervals the carpet covers completely (tiles[j][1] - li + 1 <= carpetLen), keeping s, the number of tiles in them.
The next interval j, if any, may be covered partially. If the carpet reaches into it, add li + carpetLen - tiles[j][0] tiles. Update the answer, then remove interval i from s before moving to the next start.
Complexity: time O(n log n) for sorting, space O(log n).
class Solution:
def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:
tiles.sort()
n = len(tiles)
s = ans = j = 0
for i, (li, ri) in enumerate(tiles):
while j < n and tiles[j][1] - li + 1 <= carpetLen:
s += tiles[j][1] - tiles[j][0] + 1
j += 1
if j < n and li + carpetLen > tiles[j][0]:
ans = max(ans, s + li + carpetLen - tiles[j][0])
else:
ans = max(ans, s)
s -= ri - li + 1
return ans