Problem Description
Given a list of non-overlapping white tile intervals, where each interval [l, r] represents that all positions j in the range l to r are white, and an integer carpetLen that represents the length of a carpet that can be placed anywhere, find the maximum number of white tiles that can be covered by the carpet.
Key Insights
- Sort the tile intervals by their starting positions.
- Precompute a prefix sum array for quick calculation of the total white tiles in a given range of intervals.
- Use binary search to determine the farthest interval that is completely covered by a carpet starting at a given interval's start.
- Account for a possibly partially covered interval at the end to calculate the exact number of white tiles covered.
- The sliding window with binary search approach ensures efficiency even when there are many intervals.
Space and Time Complexity
Time Complexity: O(n log n) where n is the number of tile intervals (sorting and binary search in each iteration). Space Complexity: O(n) for storing the prefix sums and sorted intervals.
Solution
The solution starts by sorting the intervals. We then build a prefix sum array where each element represents the total number of white tiles from the start of the sorted list up to the current interval. For each interval, treat its start as a potential left boundary for placing the carpet. Using binary search, find the interval that the carpet reaches at the far end (start + carpetLen - 1). The fully covered intervals contribute their entire length (obtained from the prefix sum) and if a subsequent interval is only partially covered, add the overlapped portion. Update the maximum seen value over all possible placements.