leetcode 1840 两次遍历消除局部限制

此题类似于135题,但要稍微绕点弯子。
此题需要考虑到,每个楼的高度限制实际是对周围的限制加了限制,理解到这个咱们就可以想到,用两次遍历解决这个问题。此外,楼之间最高的可能性可以通过数学方式计算,由于已经消除了不可能的情况,所以肯定能算出来。
假设两边为 ( i , a ) (i,a) (i,a) ( j , b ) (j,b) (j,b),假设中间最高楼层是 c c c,那么可以得到公式 ( c − a − 1 ) + ( c − b − 1 ) = j − i (c-a-1)+(c-b-1)=j-i (ca1)+(cb1)=ji
即可得到最终答案
c = f l o o r ( a + b + j − i 2 ) c = floor(\frac{a+b+j-i}{2}) c=floor(2a+b+ji)
最终要考虑的就是最右边的无线增长,看最右边的限制即可,代码如下:

class Solution {
public:
    int maxBuilding(int n, vector<vector<int>>& restrictions) {
        if(restrictions.size() == 0)return n-1;

        restrictions.push_back(vector<int>{1, 0});
        sort(restrictions.begin(), restrictions.end());
        int m = restrictions.size();

        for(int i=1;i<m;i++)
        {
            int mx_height = restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0];
            if(mx_height < restrictions[i][1])restrictions[i][1] = mx_height;
        }

        // 右限制,存最大值
        int ret = restrictions[m-1][1];
        ret = max(ret, n-restrictions[m-1][0]+restrictions[m-1][1]);
        for(int i=m-2;i>=0;i--)
        {
            int mx_height = restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0];
            if(mx_height < restrictions[i][1])restrictions[i][1] = mx_height;
            ret = max(ret, restrictions[i][1]);
        }

        // 找中间的最大值
        for(int i=1;i<m;i++)
        {
            ret = max(ret, (restrictions[i][0]-restrictions[i-1][0]+\
                restrictions[i][1]+restrictions[i-1][1])/2);
        }

        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值