AcWing 131. 【java】直方图中最大的矩形
原题链接
简单
作者:
tt2767
,
2019-12-07 00:34:18
,
所有人可见
,
阅读 922
// 单调栈维护左右边界,非坐标变换
import java.util.*;
// 单调栈找最小边界
// 哨兵减少栈底空值判断
// 比较的是值,而维护的是坐标
public class Main{
void calcL(int[] left, int n){
stack.clear();
stack.push(0);
for (int i = 1 ; i <= n ; i++){
while (h[stack.peek()] >= h[i]) stack.pop();
left[i] = stack.peek() + 1;
stack.push(i);
}
}
void calcR(int[] right, int n){
stack.clear();
stack.push(n+1);
for (int i = n; i>= 1 ; i--){
while (h[stack.peek()] >= h[i]) stack.pop();
right[i] = stack.peek() - 1;
stack.push(i);
}
}
void run(){
while (true){
int n = jin.nextInt();
if (n == 0){
break;
}
stack.clear();
for (int i = 1; i <= n ;i++){
int x = jin.nextInt();
h[i] = x;
}
h[0] = -1;
h[n+1] = -1;
calcL(left, n);
calcR(right, n);
long res = Integer.MIN_VALUE;
for (int i = 1; i <= n; i++){
res = Math.max(res, h[i] * (right[i] - left[i] + 1L));
}
System.out.println(res);
}
}
private Stack<Integer> stack = new Stack<>();
private int[] h = new int[100002];
private int[] left = new int[100002];
private int[] right = new int[100002];
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception {new Main().run();}
}