LeetCode-maximal-rectangle (area of maximum matrix)

Title Description

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 =10unit.

For example,
Given height =[2,1,5,6,2,3],
return10.

Algorithms ideas:

Please refer to: https://blog.csdn.net/u012534831/article/details/74356851

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int n=static_cast<int>(height.size());
        if(n<=0) return 0;
        int ans=0,num;
        stack<int>st;
        st.push(-1);
        for(int i=0;i<n;++i)
        {
            while(st.top()!=-1&&height[i]<height[st.top()])
            {
                num=st.top();
                st.pop();
                ans=max(ans,(i-st.top()-1)*height[num]);
            }
            st.push(i);
        }
        while(st.top()!=-1)
            {
                num=st.top();
                st.pop();
                ans=max(ans,(n-st.top()-1)*height[num]);
            }
        return ans;
    }
};

The same algorithm to expand:

Title Description

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

Respectively through each row, the rows and each traversed seen more portions of the maximum area histogram, and finally through all the results, selecting the maximum value.

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        int m=matrix.size();
        if(m<=0) return 0;
        int n=matrix[0].size();
        vector<int>h(n);
        fill(h.begin(),h.end(),0);
        int num;
        int ans=0;
        stack<int>st;
        st.push(-1);
        for(int i=0;i<m;++i)
        {
            for(int j=0;j<n;++j)
            {
                if(matrix[i][j]=='1')
                    ++h[j];
                else
                    h[j]=0;
            }
            for(int j=0;j<n;++j)
            {
                while(st.top()!=-1&&h[j]<h[st.top()])
                {
                    num=st.top();
                    st.pop();
                    ans=max(ans,(j-1-st.top())*h[num]);
                }
                st.push(j);
            }
            while(st.top()!=-1)
            {
                num=st.top();
                st.pop();
                ans=max(ans,(n-1-st.top())*h[num]);
            }    
        }
        return ans;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_43871369/article/details/91356311