package com.heu.wsq.leetcode.monotone_stack;
import java.util.ArrayDeque;
import java.util.Deque;
public class LargestRectangleArea {
public int largestRectangleArea(int[] heights){
int n = heights.length;
int maxArea = 0;
for (int i = 0; i < n; i++){
int width = 1;
for(int j = i + 1; j < n; j++){
if (heights[j] >= heights[i]){
width++;
}else{
break;
}
}
for (int j = i - 1; j >= 0; j--){
if (heights[j] >= heights[i]){
width++;
}else{
break;
}
}
maxArea = Math.max(width * heights[i], maxArea);
}
return maxArea;
}
public int largestRectangleArea2(int[] heights){
int n = heights.length;
if (n == 0){
return 0;
}
if (n == 1){
return heights[0];
}
Deque<Integer> stack = new ArrayDeque<>();
int area = 0;
for (int i = 0; i < n; i++){
while (!stack.isEmpty() && heights[stack.peekLast()] > heights[i]){
int height = heights[stack.removeLast()];
int width;
if (stack.isEmpty()){
width = i;
}else{
width = i - stack.peekLast() -1;
}
area = Math.max(area, height * width);
}
stack.addLast(i);
}
while (!stack.isEmpty()){
int height = heights[stack.removeLast()];
int width;
if (stack.isEmpty()){
width = n;
}else{
width = n - stack.peekLast() - 1;
}
area = Math.max(area, width * height);
}
return area;
}
public int largestRectangleArea3(int[] heights){
int n = heights.length;
if (n == 0){
return 0;
}
if (n == 1){
return heights[0];
}
Deque<Integer> stack = new ArrayDeque<>();
int area = 0;
int[] newHeights = new int[n + 2];
System.arraycopy(heights, 0, newHeights, 1, n);
stack.addLast(newHeights[0]);
for (int i = 1; i < n + 2; i++){
while(newHeights[stack.peekLast()] > newHeights[i]){
int height = newHeights[stack.removeLast()];
int width = i - stack.peekLast() - 1;
area = Math.max(area, height * width);
}
stack.addLast(i);
}
return area;
}
public static void main(String[] args) {
int[] heights = {2, 1, 5, 6, 2, 3};
LargestRectangleArea lr = new LargestRectangleArea();
int ans = lr.largestRectangleArea3(heights);
System.out.println(ans);
}
}