LeetCode 84. 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.


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 heights = [2,1,5,6,2,3],
return 10.


The basic idea to maintain a stack which only stores the increasing numbers' index and calculate the invalid index number's area on-fly. Because small values can cover large range of indexes then larger values.

In the given example: (stack stores the index number)

maxArea = 0, Stack [0] , i = 1 (i is the index for the given heights)

    heights[1] < heights[stack.top()] ---> we need to pop stack.top out and at the same time calculate the top values' area.

maxArea: 2, stack[1], i = 2;

   heights[i] > heights[stack.top()] --> push i into stack.

maxArea: 2, stack[1, 2], i = 3;

   heights[i] > heights[stack.top()] --> push i into stack

maxArea 2, stack[1, 2, 3], i =4   // in this case, we need to consider the stack.empty case.

  heights[i] < heights[stack.top()] --> we need to pop out all the stack values which is larger then current value.

maxArea 10, stack[1, 4] , i = 5

  heights[i] > heights[stack.top()] --> push i into stack.

maxArea 10, stack [1, 4, 5], i = 6.

    Now, we need to pop value one by one and caculate the maxArea.

#include <vector>
#include <stack>
#include <iostream>
#include <climits>
using namespace std;

/*
  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.
*/

int largestRectangleArea(vector<int>& heights) {
  stack<int> index;
  int n = heights.size();
  int maxArea = 0;
  int i = 0;
  while(i < n) {
    while(!index.empty() && (heights[i] < heights[index.top()])) {
      int tmp = index.top();
      index.pop();
      maxArea = max(maxArea, heights[tmp] * (i - (index.empty() ? 0 : index.top() +  1)));
    }
    index.push(i++);
  }
  while(!index.empty()) {
    int tmp = index.top();
    index.pop();
    maxArea = max(maxArea, heights[tmp] * (n - (index.empty() ? 0 : index.top() + 1)));
  }
  return maxArea;
}

int main(void) {
  vector<int> heights{2, 1, 5, 6, 2, 3};
  cout << largestRectangleArea(heights) << endl;
}
  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值