Maximum White Tiles Covered by a Carpet — LeetCode 2271 Python Solution
- Problem
- #2271
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white. You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.
Example
- Input
- tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10
- Output
- 9
- Explanation
- Place the carpet starting on tile 10.
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2271. Maximum White Tiles Covered by a Carpet is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2271. Maximum White Tiles Covered by a Carpet?
- LeetCode 2271. Maximum White Tiles Covered by a Carpet is rated Medium on LeetCode.
- What topics does LeetCode 2271. Maximum White Tiles Covered by a Carpet cover?
- LeetCode 2271. Maximum White Tiles Covered by a Carpet is tagged Greedy, Array, Binary Search, Prefix Sum, Sorting and Sliding Window on LeetCode.