LeetCode - Largest Rectangle in Histogram 题解

来源:互联网 发布:linux查看sd卡 编辑:程序博客网 时间:2024/05/17 03:08

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.

思路:

首先可以想到沿每个点向左向右延伸,O(N^2)

这样太慢,想到可以将左边的低点一个个保存下来,可以直接计算。

于是可以用一个栈维护一个递增序列,每遇到一个点就将原先栈里比当前点高的点出栈,每次出栈时以出栈点为中心更新一下最大值。

class Solution {private:    int maxx;public:    int largestRectangleArea(vector<int> &height) {        maxx = 0;        height.push_back(-1);        int num = height.size();        stack<int> S;        for(int i = 0; i < num; i++){            if(S.empty() || height[S.top()] < height[i]) {                S.push(i);            }            else{                while(!S.empty() && height[S.top()] >= height[i]){                    int k = S.top();                    S.pop();                    if(!S.empty()){                        maxx = max(maxx, height[k] * (i - 1 - S.top()));                    }                    else{                        maxx = max(maxx, height[k] * i);                    }                }                S.push(i);            }        }        return maxx;    }};


0 0
原创粉丝点击