找到真正的限制是关键
解题思路
如果高度限制就是建筑物的高度,那么最大值就很好求了;
朴素的思路是多源BFS,但数据量太大,肯定不能求出每个建筑物的高度;
所以可以贪心的只求确定高度建筑范围内的最大值;
分情况讨论后可归纳公式为max(height, last_height) + (dis - abs(height - last_height)) / 2;
但是给出的限制并不是真实的限制,会虚高,真实的限制只会更低;
左边的限制会影响右边的限制,同时右边也会影响左边;
左右两边的高度差最大不能超过其距离差(相邻位置最大高度差为1);
所以从左到右,再从右到左,将虚高的限制降低;
最左边限制为位置1高度0,最右边为位置n高度n-1;
因为给出的建筑并非有序,所以需要先按位置升序排一下;
代码
class Solution {
public:
int maxBuilding(int n, vector<vector<int>>& restrictions) {
sort(restrictions.begin(), restrictions.end());
int rsize = restrictions.size();
int last_pos = 1, last_height = 0;
int ans = 0;
for(int i = 0; i < rsize; i++) {
int pos = restrictions[i][0], height = restrictions[i][1];
int dis = pos - last_pos;
if(height > last_height + dis) restrictions[i][1] = last_height + dis;
last_pos = pos; last_height = restrictions[i][1];
}
last_pos = n; last_height = n - 1;
for(int i = rsize - 1; i >= 0; i--) {
int pos = restrictions[i][0], height = restrictions[i][1];
int dis = last_pos - pos;
if(height > last_height + dis) restrictions[i][1] = last_height + dis;
last_pos = pos; last_height = restrictions[i][1];
}
//for(auto r : restrictions) cout << r[0] << r[1] << endl;
last_pos = 1; last_height = 0;
for(int i = 0; i < rsize; i++) {
int pos = restrictions[i][0], height = restrictions[i][1];
int dis = pos - last_pos;
ans = max(ans, max(height, last_height) + (dis - abs(height - last_height)) / 2);
last_pos = pos; last_height = height;
}
return max(ans, last_height + n - last_pos);
}
};