1. package stack.code84;
    2. import java.util.Stack;
    3. public class Solution {
    4. public int largestRectangleArea(int[] heights) {
    5. //用作返回的答案
    6. int res = 0;
    7. //用来存储满足单调性的矩形的栈
    8. Stack<Rect> stack = new Stack<>();
    9. //在数组后面增加一个0,是代码整洁,最后可以清空栈
    10. heights = arrPushBack(heights,0);
    11. //遍历数组,也就是便利矩形网格
    12. for(int height : heights){
    13. //记录累加宽度
    14. int leijiaWidth = 0;
    15. //如果栈不为空且
    16. //栈顶矩形的高度,大于当前高度了。说明单调性被破坏了。则需要进行如下操作
    17. while (!stack.isEmpty() && stack.peek().heigh >= height){
    18. leijiaWidth = stack.peek().width + leijiaWidth;
    19. res = Math.max(res,stack.peek().heigh * leijiaWidth);
    20. stack.pop();
    21. }
    22. stack.push(new Rect(leijiaWidth + 1,height));
    23. }
    24. return res;
    25. }
    26. public int[] arrPushBack(int[] arr,int value){
    27. int[] newArr = new int[arr.length + 1];
    28. for(int i = 0 ; i < arr.length;i++){
    29. newArr[i] = arr[i];
    30. }
    31. newArr[arr.length] = value;
    32. return newArr;
    33. }
    34. /**
    35. * 定义一个矩形对象,有宽和高两个属性
    36. */
    37. class Rect{
    38. int width;
    39. int heigh;
    40. public Rect(int width, int heigh) {
    41. this.width = width;
    42. this.heigh = heigh;
    43. }
    44. }
    45. }