leetcode 84. 柱状图中最大的矩形 单调栈O(N)

就是找以当前位置为最小值的最大延展区间

暴力O(n^3)超时 大多数的样例是过了的

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int ret = 0;
        for(int i=0;i<heights.size();i++){
            for(int j=i;j<heights.size();j++){
                int min1 = INT_MAX;
                for(int k=i;k<=j;k++){
                    min1 = min(heights[k],min1);
                }
                ret = max(ret,min1* ( j-i+1) );
            }
        }
        return ret;
    }
};

leetcode 84. 柱状图中最大的矩形 单调栈O(N)_第1张图片

dp

//dp尝试1 O(N^2) 依旧超时
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        if(heights.size()==0){
            return 0;
        }else if(heights.size()==1){
            return heights[0];
        }
        vector<int>dp(heights);
        int ret = 0;
        for(int i=0;i<heights.size();i++){
            int min1 = heights[i];
            for(int j=i+1;j<heights.size();j++){
                min1 = min(min1,heights[j]);
                dp[j] = max( dp[j],(j-i+1)*min1 );
            }
            ret = max(dp[i],ret);
        }
        return ret;
    }
};

单调栈

https://blog.csdn.net/zark721/article/details/78279770
每个元素是入栈出栈一次 时间O(N)

//单调栈
struct point{
    int x,y;
    int val;
    point(int pos,int val):x(pos),y(pos),val(val){}
    point(){}
};
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<point> st;
        int ret = 0;
        for(int i = 0;i < heights.size();i ++){
            if(st.empty()){
                st.push(point(i,heights[i]));
            }else{

                 if( st.top().val < heights[i]){
                    //st.top().y = i;
                    st.push(point(i,heights[i]));
                 }else{

                    point ptt(i,heights[i]);
                    while(!st.empty() && st.top().val >= heights[i] ){
                        point pt = st.top();
                        st.pop();
                        //debug(pt.val);
                        //debug(pt.x);
                        //debug(pt.y);
                        ret = max(ret, (pt.y-pt.x+1)*pt.val );
                        if(!st.empty()){
                            st.top().y = pt.y;
                        }
                        ptt.x = pt.x;
                    }

                    if(!st.empty()){
                        st.top().y = ptt.y;
                    }
                    st.push( ptt );
                 }
            }
        }
        while(!st.empty()){
            point pt = st.top();
            st.pop();
            if(!st.empty()){
                st.top().y = pt.y;
            }
            ret = max(ret, (pt.y-pt.x+1)*pt.val );
            //debug(pt.val);
            //debug(pt.x);
            //debug(pt.y);
        }
        //debug(ret);
        return ret;
    }
};

leetcode 84. 柱状图中最大的矩形 单调栈O(N)_第2张图片

你可能感兴趣的:(#,Leetcode)