zoukankan      html  css  js  c++  java
  • Largest Rectangle in Histogram

    Largest Rectangle in Histogram

     Total Accepted: 18582 Total Submissions: 86792My Submissions

    Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.


    Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].


    The largest rectangle is shown in the shaded area, which has area = 10 unit.

    For example,
    Given height = [2,1,5,6,2,3],
    return 10.

    Have you been asked this question in an interview? 

    public class Solution {
             public int largestRectangleArea(int[] height) {
            int [] leftSmall = new int[height.length];
            int [] rightSmall = new int[height.length];
            Stack<PositionNode> smallStack = new Stack<PositionNode>();
            for (int i = 0; i < height.length; i++) {
                while (!smallStack.isEmpty() && smallStack.peek().height >= height[i]){
                    smallStack.pop();
                }
                if (!smallStack.isEmpty()) 
                {
                    leftSmall[i] = smallStack.peek().pos;
                 }  else {
                    leftSmall[i] = -1;
                 }
                smallStack.push(new PositionNode(i,height[i]));
            }
                smallStack.clear();
              for (int i = height.length - 1; i > -1; i--) {
                  while (!smallStack.isEmpty() && smallStack.peek().height >= height[i]){
                    smallStack.pop();
                }
                if (!smallStack.isEmpty()) {
                    rightSmall[i] = smallStack.peek().pos;
                }
                 else {
                     rightSmall[i] = height.length ;
                 }
                PositionNode newNode = new PositionNode(i,height[i]);
                smallStack.push(newNode);
            }
            int maxArea = 0;
            for (int i = 0; i < height.length; i++) {
                int thisArea = height[i] * Math.abs(rightSmall[i] - leftSmall[i] - 1);
                maxArea = Math.max(maxArea,thisArea);
            }
            return maxArea;
        }
        class PositionNode {
            int pos;
            int height;
            public PositionNode(int pos, int height) {
                this.pos = pos;
                this.height = height;
            }
        }
    }



    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    WannaMine4.0查杀方法
    kthrotlds(WatchDogs变种)查杀方法
    Powershell无文件挖矿查杀方法
    Myking&暗云III病毒查杀方法
    NAT ALG原理与应用
    Invoke-PSImage 使用简介
    Cobaltstrike 安装
    windows 创建、启动、删除、停止服务
    CobaltStrike 之 Attacks 菜单解析
    网络安全法(2016年11月7日发布 2017年6月1日起施行 主席令(第五十三号)公布)
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4710564.html
Copyright © 2011-2022 走看看