阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述 共有编号 1~n 的一排建筑,约束规则:
restrictions = [[id, maxHeight]],代表编号 id 的建筑高度不能超过 maxHeight; 求所有建筑能达到的最大高度。示例
输入:n = 10, restrictions = [[5,3],[2,5],[7,4]] 输出:5
(间距 + 左高度 + 右高度) / 2;package lc1800_lc1899.lc1840;
import java.util.Arrays;
import java.util.Comparator;
class Solution {
public int maxBuilding(int n, int[][] restrictions) {
if (restrictions == null || restrictions.length == 0) {
return n - 1;
}
Arrays.sort(restrictions, Comparator.comparingInt(a -> a[0]));
int m = restrictions.length;
int prevIdx = 1;
int prevH = 0;
for (int i = 0; i < m; i++) {
int idx = restrictions[i][0];
int limit = restrictions[i][1];
int maxCan = prevH + (idx - prevIdx);
restrictions[i][1] = Math.min(limit, maxCan);
prevIdx = idx;
prevH = restrictions[i][1];
}
prevIdx = n;
prevH = n - 1;
for (int i = m - 1; i >= 0; i--) {
int idx = restrictions[i][0];
int limit = restrictions[i][1];
int maxCan = prevH + (prevIdx - idx);
restrictions[i][1] = Math.min(limit, maxCan);
prevIdx = idx;
prevH = restrictions[i][1];
}
int res = 0;
prevIdx = 1;
prevH = 0;
for (int i = 0; i < m; i++) {
int curIdx = restrictions[i][0];
int curH = restrictions[i][1];
int dist = curIdx - prevIdx;
int midMax = (dist + prevH + curH) / 2;
res = Math.max(res, midMax);
prevIdx = curIdx;
prevH = curH;
}
res = Math.max(res, prevH + (n - prevIdx));
return res;
}
}class Solution {
public int maxBuilding(int n, int[][] restrictions) {
int m = restrictions.length;
// 无限制直接返回n-1
if (m == 0) {
return n - 1;
}
// 按建筑编号升序排序限制条件
Arrays.sort(restrictions, (a, b) -> a[0] - b[0]);
// h数组存储每个限制建筑修正后的合法最大高度
int[] h = new int[m];
// 正向遍历:从1号建筑向右收紧高度上限
h[0] = Math.min(restrictions[0][0] - 1, restrictions[0][1]);
for (int i = 1; i < m; i++) {
h[i] = Math.min(h[i - 1] + restrictions[i][0] - restrictions[i - 1][0], restrictions[i][1]);
}
// 反向遍历:从右向左再次收紧高度上限
for (int i = m - 2; i >= 0; i--) {
h[i] = Math.min(h[i], h[i + 1] + restrictions[i + 1][0] - restrictions[i][0]);
}
// 初始化答案:第一段1到首个限制的峰值 + 最后一个限制到n的峰值
int ans = Math.max((restrictions[0][0] - 1 + h[0]) / 2, h[m - 1] + n - restrictions[m - 1][0]);
// 遍历相邻限制区间,计算区间内可达到的最高峰值
for (int i = 0; i < m - 1; i++) {
ans = Math.max(ans, (restrictions[i + 1][0] - restrictions[i][0] + h[i] + h[i + 1]) / 2);
}
return ans;
}
}