**LeetCode 84. Largest Rectangle in Histogram

https://leetcode.com/problems/largest-rectangle-in-histogram/

O(2n)  至少做过两次,一次是清华的机考准备的时候,一次是ACM的时候,现在仍然想了挺久没搞定,,,,


其实问题就是找一个StartIdx 和EndIdx 看两个idx之间的面积。

关键点在于:考虑“峰”的面积,并且两边不去计算。。。具体看这里的详解:

http://www.cnblogs.com/felixfang/p/3676193.html

http://www.cnblogs.com/avril/archive/2013/08/24/3278873.html


#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
#include <algorithm>
#include <vector>

using namespace std;

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        heights.push_back(0);
        stack <int> sta;
        //sta.push_back(0);
        int ret=0;
        for( int i=0; i<heights.size(); i++ ) {
                while( !sta.empty() &&  heights[sta.top()]>heights[i] ) {
                    int idx = sta.top();
                    sta.pop();
                    int width = sta.empty()? i : (i-sta.top()-1);
                    ret = max( ret, heights[idx]*width );
                }
            sta.push(i);
        }
        return ret;
    }
};

int main() {
    freopen("84.txt", "r", stdin);
    int n;
    while( cin >> n ) {
        int in;
        vector <int> nums;
        for( int i=0;i<n;i++ ) {
            cin >> in;
            nums.push_back(in);
        }
        Solution s;
        cout << s.largestRectangleArea(nums) << endl;
    }
    return 0;

}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值