2271. Maximum White Tiles Covered by a Carpet (Binary Search)

这篇博客探讨了一种解决瓷砖覆盖问题的方法。通过计算小于地毯长度的瓷砖之和,然后使用排序和二分查找来降低时间复杂度到O(n log n),避免了超时错误。文章特别关注了边界条件,如索引为0和最后一个索引的情况,并提供了详细的代码实现。
摘要由CSDN通过智能技术生成

The idea of the solution is that we calculate the sum of the tiles that smaller than the index + carpet length. This is pretty straightforward and intuitive. What if the index + carpet length is larger than the tiles' left index but smaller than its right index? we add it manually.

However, we notice that if we just use a linear search, the Time complexity of our program would be O(n^2) which will cause TLE. Thus, we want to use NlogN to sort the tiles first and then do a binary search on the tiles' ending index.

The only edge case is the index equals 0 and the last index. As we want to check the next tile of the index we found if it contains a part of our answer.

class Solution {
public:
    int binarySearch(int target, vector<vector<int>>& end){
        int l = 0, r = end.size() - 1,mid;
        while(l <= r){
            mid=l+(r - l)/2;
            if(end[mid][1] > target) r = mid - 1;
            else {l = mid + 1;}
        }
        return l - 1;
    }
    int maximumWhiteTiles(vector<vector<int>>& tiles, int carpetLen) {
        int n = tiles.size();
        sort(tiles.begin(), tiles.end());
        vector<int> prefix_sum(n, 0);
        prefix_sum[0] = tiles[0][1] - tiles[0][0] + 1;
        for(int i = 1; i < n; i++)prefix_sum[i] = prefix_sum[i - 1] + (tiles[i][1] - tiles[i][0] + 1);
        int ans = 0, part, cur, indx;
        for(int i = 0; i < n; i++){
            cur = tiles[i][0] + carpetLen - 1;
            indx = binarySearch(cur, tiles);
            if(indx == -1){
                part = cur - tiles[indx + 1][0] + 1;
                ans = max(part,ans);
                continue;
            }
            if(i > 0){
                part = prefix_sum[indx] - prefix_sum[i - 1];
            }else part = prefix_sum[indx];
            if(indx < n - 1 && cur >= tiles[indx + 1][0]){
                part += cur - tiles[indx + 1][0] + 1; 
            }
            ans = max(ans, part);
        }
        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值