【Leetcode】84.柱状图中的最大矩形C++(暴力破解法)

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

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

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

#include "iostream"

#include "vector"

#include "stack"

using namespace std;

class Solution
{
public:
    int largestRectangleArea(vector<int> &heights)
    {
        int size = heights.size();

        if (size == 1)
        {
            return heights[0];
        }

        int h = -1, ans = 0, area, j;
        for (int i = 0; i < size; i++)
        {
            while (heights[i] == h && i < size-1)
            {
                i++;
            }
            h = heights[i];
            area = h;
            j = 1;
            while (i - j >= 0 && heights[i - j] >= h)
            {
                area += h;
                j++;
            }
            j = 1;
            while (i + j < size && heights[i + j] >= h)
            {
                area += h;
                j++;
            }
            ans = ans > area ? ans : area;
        }
        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/104093816