084. Largest Rectangle in Histogram

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.
Below 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 =10unit.
For example,
Given heights =[2,1,5,6,2,3],
return10.


My solution used the monotone stack with time complexity O(N).

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
      if(heights.size() == 0) return 0;
      heights.push_back(0);
      stack<int> myStack;
      int maxArea = 0;
      for(int i = 0; i < heights.size(); i++){
        if(myStack.empty() || heights[i] > heights[myStack.top()]){
          myStack.push(i);
        }else{
          int top = heights[myStack.top()];
          myStack.pop();
          int width = i - (myStack.empty() ? -1 : myStack.top()) - 1;
          maxArea = max(maxArea, top*width);
          i--;
        }
      }
      return maxArea;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 金句:1.每一次说不懂的机会,都会成为我们人生的转折点。2.一头猪好好被夸奖一番,它就能爬到树上去。3.知识原本是...
    喜斯陶阅读 4,427评论 0 0
  • 这是个熬煎的10月。它使我成长了10年以上的人生阅历和见识。硬要总结的话,还是有许多经验教训可以与人分享的。 但是...
    香杉阅读 1,001评论 0 0
  • 沐一翎 一个放荡不羁爱自由的girl 喜欢一个人安静的待着但又害怕孤独 对爱的人可以献出生命但对于不重要的人眼神都...
    一袭白衣仅是你阅读 2,463评论 0 0
  • 最近一直在思考一个问题:为什么20几岁的我,会对生活、工作充斥着迷茫呢? 我觉得原因有很多,首先是社会大环境的影响...
    panny7116阅读 3,821评论 0 51