单调栈--最大矩形

一.题目描述

84. 柱状图中最大的矩形 - 力扣(LeetCode)

示意图

1.可以直接暴力做题,从左到右遍历每一列上的每一个,但超时不多赘述

#include<iostream>
using namespace std;
const int maxsize = 1e5 + 3;
int arr[maxsize];
int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> arr[i];
	}
	int ans = 0; int res = 0;
	for (int i = 1; i <= n; i++)
	{
		ans = 0;
		int j = i;
		int now = arr[i];
		ans = arr[i];
		while (now <= arr[i + 1]&&i<=n)
		{
			ans += now;
			i++;
		}
		i = j;
		while (now<=arr[i-1]&&i>=1)
		{
			ans += now;
			i--;
		}
		if (res<=ans)
		{
			res = ans;
		}
		i = j;
	}
	cout << res;
}

2.单调栈

通过先读取,当栈顶的元素的值小与当前的元素,那么该元素压入栈中;当栈顶的值小于当前的值,那么弹出栈顶的值并计算最大面积(一直判断弹出,直到该元素大与栈顶的值),当空栈时,即为栈顶的值为0,继续判断

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
          stack<int> st;
        heights.push_back(0);//结尾虚拟柱子高度0
        int size = heights.size();
        int res = 0;
        for (int i = 0; i < size; ++i)
        {
            while (!st.empty() && heights[st.top()] >= heights[i])
            {
                int val = st.top();
                st.pop();
                if (!st.empty())
                    res = max(res, heights[val] * (i - st.top() - 1));
                else
                {
                    res = max(res, heights[val] * i);
                }
               //宽度不包含当前元素
            }
            st.push(i);
        }
        return res;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值