AcWing 131. 直方图中最大的矩形——Java代码版——单调栈
原题链接
简单
作者:
三玖天下第一
,
2021-03-25 16:28:53
,
所有人可见
,
阅读 586
import java.io.*;
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] temp = reader.readLine().split(" ");
//都多申请几位,方便处理边界
ArrayDeque<Integer> queue = new ArrayDeque<>(100000 + 10);
int[] h = new int[100000 +2];
int[] l = new int[100000 +2];
int[] r = new int[100000 +2];
h[0] = -1;//将左边界初始化为-1,方便进行边界判断
while(Integer.parseInt(temp[0]) != 0){
int n = Integer.parseInt(temp[0]);
h[n+1] = -1;//同上
for (int i = 1; i <= n; i++) {
h[i] = Integer.parseInt(temp[i]);
}
//计算出左侧第一个比当前数小的数据的位置
queue.push(0);
for (int i = 1; i <= n; i++) {
while(h[i] <= h[queue.peek()]){
queue.pop();
}
l[i] = queue.peek();
queue.push(i);
}
queue.clear();
//计算出右侧第一个比当前数小的数据的位置
queue.push(n+1);
for (int i = n; i > 0; i--) {
while(h[i] <= h[queue.peek()]){
queue.pop();
}
r[i] = queue.peek();
queue.push(i);
}
long res = 0;
for (int i = 1; i <= n; i++) {
//这里在计算时一定要手动强转为long,不然会按照int计算
res = Math.max(res, (long)h[i]*(r[i] - l[i] - 1));
}
writer.write(res+"\n");
temp = reader.readLine().split(" ");
}
writer.flush();
}
}
谢谢你写的题解!