纵有疾风起
人生不言弃

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.

Largest Rectangle in Histogram插图

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

 

Largest Rectangle in Histogram插图1

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;
}

 

转载于:https://www.cnblogs.com/wuchanming/p/4130764.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/97950252

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

未经允许不得转载:起风网 » Largest Rectangle in Histogram
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录