【Leetcode】84.柱状图中的最大矩形C++(单调栈法)

在这里插入图片描述
在这里插入图片描述

// 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

// 求在该柱状图中,能够勾勒出来的矩形的最大面积。

#include "iostream"

#include "vector"

#include "stack"

using namespace std;

class Solution
{
public:
    int largestRectangleArea(vector<int> &heights)
    {
        stack<int> z;
        z.push(-1);
        int n = heights.size();
        int ans = 0, tmp;
        for (int i = 0; i < n; ++i)
        {
            while (z.top() != -1 && heights[z.top()] > heights[i])
            {
                int tmp = z.top();
                z.pop();
                tmp = heights[tmp] * (i - 1 - z.top());
                ans = ans > tmp ? ans : tmp;
            }
            z.push(i);
        }
        while (z.top() != -1)
        {
            int tmp = z.top();
            z.pop();
            tmp = heights[tmp] * (n - 1 - z.top());
            ans = ans > tmp ? ans : tmp;
        }
        return ans;
    }
};

int main(int argc, char const *argv[])
{
    vector<int> height;
    int x;

    while (true)
    {
        cin >> x;
        height.push_back(x);
        if (cin.get() == '\n')
            break;
    }

    Solution so;
    cout << so.largestRectangleArea(height);

    return 0;
}
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104094543