#2271
Maximum White Tiles Covered by a Carpet
MediumArrayBinary SearchGreedySliding WindowSortingPrefix SumSliding WindowPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach uses a sliding window technique combined with prefix sums to efficiently calculate the maximum number of white tiles that can be covered by the carpet. This significantly reduces the time complexity by avoiding redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Sort the tiles based on their starting position.
- 2Step 2: Create a prefix sum array to store the cumulative number of white tiles covered up to each tile.
- 3Step 3: Use a sliding window to determine the maximum number of tiles covered by placing the carpet starting from each tile's position.
solution.py18 lines
1# Full working Python code
2
3def maxWhiteTiles(tiles, carpetLen):
4 tiles.sort()
5 prefix_sum = [0] * (len(tiles) + 1)
6 for i in range(len(tiles)):
7 prefix_sum[i + 1] = prefix_sum[i] + (tiles[i][1] - tiles[i][0] + 1)
8 max_covered = 0
9 j = 0
10 for i in range(len(tiles)):
11 while j < len(tiles) and tiles[j][0] <= tiles[i][0] + carpetLen:
12 j += 1
13 covered = prefix_sum[j] - prefix_sum[i]
14 if j > 0 and tiles[j - 1][1] > tiles[i][0] + carpetLen:
15 covered -= tiles[j - 1][1] - (tiles[i][0] + carpetLen)
16 max_covered = max(max_covered, covered)
17 return max_covered
18ℹ
Complexity note: The sorting step takes O(n log n), and the sliding window approach runs in O(n), making this overall efficient.
- 1The placement of the carpet can be optimized by considering the starting position of each tile.
- 2Using prefix sums allows for quick calculations of the total number of covered tiles.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.