[LeetCode] 84. Largest Rectangle in Histogram

[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.


要求这个直方图里面面积最大的长方形是多少面积。
对朴素的想法是,对每一个元素h[i],往左找直到h[l] < h[i],往右找直到h[r] < h[i],r-l为i的宽度,从而求面积(r-l)*i。复杂度为O(n*n),超时了。。。
用栈优化,栈内元素为(数值,直到当前的长度)-(val, cnt),保持栈顶数值是最大的元素。对元素h[i],若比栈顶小,则pop出来,计算面积,然后压栈(h[i], cnt+tmp_cnt)。
举个例子,[2,1,5,6,2,3]。

(2, 1)

此时h[i] = 1, tmp_cnt = 0。

  • 1 < 2:tmp_cnt += cnt = 1, 面积=2*1, 出栈;
  • 栈空:压栈(1, 1+tmp_cnt) = (1, 2);

(1, 2)

5和6都能保证栈顶val是最大的:

(1, 2), (5, 1), (6, 1)

此时h[i] = 2。
tmp_cnt=0。

  • 2 < 6:tmp_cnt += cnt = 1, 面积=6*1,出栈;
  • 2 < 5:tmp_cnt += cnt = 2, 面积=5*2,出栈;
  • 2 > 1:压栈(2, cnt+tmp_cnt) = (2, 3)。

(1, 2), (2, 3)

3也能保证栈顶val最大:

(1, 2), (2, 3), (3, 1)

最后重复一遍上述出栈步骤: tmp_cnt = 0。

  • tmp_cnt += cnt = 1, 面积=3*1,出栈;
  • tmp_cnt += cnt = 4, 面积=2*4,出栈;
  • tmp_cnt += cnt = 6, 面积=1*6,出栈;

最终面积最大的是5*2=10。


class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        stack<int> cnt_st;
        int len = heights.size();
        int res = 0;
        for (int i=0; i<len; ++i) {
            int cnt = 0;
            if (!st.empty() && st.top() > heights[i]) {
                while (!st.empty() && st.top() > heights[i]) {
                    int tmp = st.top();
                    st.pop();
                    cnt += cnt_st.top();
                    cnt_st.pop();
                    if (res < tmp*cnt) res = tmp*cnt;
                }
            }
            st.push(heights[i]);
            cnt_st.push(cnt+1);
        }
        int cnt = 0;
        while (!st.empty()) {
            int tmp = st.top();
            st.pop();
            cnt += cnt_st.top();
            cnt_st.pop();
            if (res < tmp*cnt) res = tmp*cnt;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值