AcWing 131. 直方图中最大的矩形(Java)
原题链接
简单
作者:
peilin
,
2020-07-07 04:50:33
,
所有人可见
,
阅读 597
Java 代码
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while(n != 0) {
int[] height = new int[n+1];
for(int i = 0; i < n; i++) {
height[i] = scanner.nextInt();
}
height[n] = 0;
Deque<Rectangle> stack = new ArrayDeque<>();
stack.push(new Rectangle(height[0], 1));
long ans = 0;
for(int i = 1; i <= n; i++) {
if(stack.peek().h < height[i]) stack.push(new Rectangle(height[i], 1));
else {
int width = 0;
while(!stack.isEmpty() && stack.peek().h >= height[i]) {
Rectangle rectangle = stack.pop();
width += rectangle.w;
ans = Math.max(ans, (long) rectangle.h * width);
}
stack.push( new Rectangle(height[i], width + 1) );
}
}
System.out.println(ans);
n = scanner.nextInt();
}
}
}
class Rectangle {
int h, w;
public Rectangle(int h, int w) {
this.h = h;
this.w = w;
}
}