Maximum White Tiles Covered by a Carpet - 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.

Return the maximum number of white tiles that can be covered by the carpet.

Input & Output

Example 1 — Basic Case
$ Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10
Output: 9
💡 Note: Place carpet from position 10 to 19. It covers tiles [10,11] (2 tiles), [12,18] (7 tiles), totaling 9 tiles.
Example 2 — Optimal Positioning
$ Input: tiles = [[10,11],[1,1]], carpetLen = 2
Output: 2
💡 Note: Place carpet from position 10 to 11, covering both tiles [10,11] completely for 2 tiles total.
Example 3 — Single Large Range
$ Input: tiles = [[1,100]], carpetLen = 10
Output: 10
💡 Note: The carpet can cover at most 10 consecutive positions from the range [1,100].

Constraints

  • 1 ≤ tiles.length ≤ 5 × 104
  • tiles[i].length == 2
  • 1 ≤ li ≤ ri ≤ 109
  • 1 ≤ carpetLen ≤ 109

Visualization

Tap to expand
Maximum White Tiles Covered by a Carpet INPUT Tiles on Number Line: [1,5] [10,11] [12,18] [20,25] [30,32] 1 10 20 30 tiles = [ [1,5], [10,11], [12,18], [20,25], [30,32] ] carpetLen = 10 Carpet (length 10): CARPET 10 units ALGORITHM STEPS 1 Sort Tiles Sort by left endpoint 2 Prefix Sum Calculate cumulative tiles 3 Sliding Window Place carpet at each start 4 Binary Search Find carpet end position Optimal Carpet Position: Carpet at [10,19] Covers: [10,11] + [12,18] = 2 + 7 = 9 tiles FINAL RESULT Maximum Tiles Covered: 9 OK - Maximum Found! Solution Breakdown: Carpet start: position 10 Carpet end: position 19 Tiles [10,11]: 2 covered Tiles [12,18]: 7 covered Total: 2 + 7 = 9 Key Insight: The optimal carpet placement always starts at the beginning of some tile interval. By using prefix sums for quick range queries and binary search to find the rightmost tile within carpet range, we achieve O(n log n) time complexity instead of brute force O(n * carpetLen). TutorialsPoint - Maximum White Tiles Covered by a Carpet | Optimal Solution
Asked in
Google 12 Microsoft 8 Amazon 6
31.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen