单调栈专题

问题驱动型分析博客:

1.

题目是这样的,给一个数组,返回一个大小相同的数组。返回的数组的第i个位置的值应当是,对于原数组中的第i个元素,至少往右走多少步,才能遇到一个比自己大的元素(如果之后没有比自己大的元素,或者已经是最后一个元素,则在返回数组的对应位置放上-1)。

简单的例子:

input: 5,3,1,2,4

return: -1 3 1 1 -1

 BONUS:

1.add 0 is important action to make sure alll elements can out of stack

2.when we see a situation we will have a static situation in our mind.But every time different situation's variable have diifferent meaning .

ONCE AGAIN:

MAKE SURE YOU understand the meaning of the variables!!!

#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<stack>
#include<climits>
//monotonic stack application
using namespace std;
class Solution {
public:
    int largestRectangleArea(vector<int> &height)
    {
        int res=0;
        //add 0 make sure all elements come out of the stack
        height.push_back(0);
        vector<int> index;
        for(int i=0;i<height.size();i++)
        {
            //find the max area height need to find the lowest one,if larger some part can't make this rectangle
            while(index.size()>0&&height[index.back()]>=height[i])
            {
                int h=height[index.back()];
                index.pop_back();
                //if still have number in stack.Means rectangle don't start with zero,-1 is to balance
                int sidx=index.size()>0?index.back():-1;
                cout<<"indexback"<<index.back()<<endl;
                cout<<"flag"<<i<<" "<<sidx<<" "<<i-sidx-1<<endl;
                //make sure the true meaning of variable is very important.
                /**
                *such as this i is the point+1,sidx is the point0-1,point-point0+1==point+1-point0+1-1
                point0&point means the rectangle's start and end
                **/
                res=max(res,h*(i-sidx-1));

            }
            index.push_back(i);

        }
        return res;
    }
};

int main()
{
    vector<int> res={2,1,5,6,2,3};
    Solution s;
    cout<<s.largestRectangleArea(res)<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/Marigolci/p/11342700.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值