- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 35 lines of C++ from the credited upstream file 2271.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maximumWhiteTiles(vector<vector<int>>& tiles, int carpetLen) {4 if (ranges::any_of(tiles, [&](const auto& tile) {5 return tile[1] - tile[0] + 1 >= carpetLen;6 }))7 return carpetLen;8 9 int ans = 0;10 vector<int> starts;11 vector<int> prefix(tiles.size() + 1);12 13 ranges::sort(tiles);14 15 for (const vector<int>& tile : tiles)16 starts.push_back(tile[0]);17 18 for (int i = 0; i < tiles.size(); ++i) {19 const int length = tiles[i][1] - tiles[i][0] + 1;20 prefix[i + 1] = prefix[i] + length;21 }22 23 for (int i = 0; i < tiles.size(); ++i) {24 const int s = tiles[i][0];25 const int carpetEnd = s + carpetLen - 1;26 const int endIndex =27 ranges::upper_bound(starts, carpetEnd) - starts.begin() - 1;28 const int notCover = max(0, tiles[endIndex][1] - carpetEnd);29 ans = max(ans, prefix[endIndex + 1] - prefix[i] - notCover);30 }31 32 return ans;33 }34};35