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

参考:http://blog.csdn.net/abcbc/article/details/8943485

C++实现代码:

#include<iostream>

#include<vector>

#include<stack>

using namespace std;



class Solution

{

public:

    int largestRectangleArea(vector<int> &height)

    {

        if(height.empty())

            return 0;

        int maxArea=0;

        int i=0;

        int n=height.size();

        stack<int> st;

        int start;

        for(i=0;i<n;i++)

        {

            if(st.empty()||height[i]>height[st.top()])

                st.push(i);

            else

            {

                start=st.top();

                st.pop();
        //注意求宽度时,是减去当前元素的前一个栈顶元素的index
int width=st.empty()?i:i-st.top()-1; maxArea=max(width*height[start],maxArea); i--;//处理到栈为空或者栈中的元素都比当前处理的元素小为止 } } while(!st.empty()) { start=st.top(); st.pop(); int width=st.empty()?n:n-st.top()-1; maxArea=max(width*height[start],maxArea); } return maxArea; } }; int main() { Solution s; vector<int> height={1,2,2}; cout<<s.largestRectangleArea(height)<<endl; }

自己写的一个O(n^2)超时了。

#include<iostream>

#include<vector>

#include<climits>

using namespace std;



class Solution {

public:

    int largestRectangleArea(vector<int> &height) {

        if(height.empty())

            return 0;

        int i,j;

        int minH;

        int maxArea=0;

        int n=height.size();

        for(i=0;i<n;i++)

        {

            minH=height[i];

            for(j=i;j<n;j++)

            {

                minH=min(minH,height[j]);

                maxArea=max(maxArea,minH*(j-i+1));

            }

        }

        return maxArea;

    }

};



int main()

{

    Solution s;

    vector<int> height={2,1,5,6,2,3};

    cout<<s.largestRectangleArea(height)<<endl;

}

 

你可能感兴趣的:(in)