柱状图中最大的矩形

#include <vector>
#include <algorithm>
#include <stack>

using namespace std;

int maxArea(std::vector<int>& arr) {
        int n = arr.size();
        std::vector<int> left(n), right(n, n);

        std::stack<int> st;
        for (int i = 0; i < n; ++i) {
            while (!st.empty() && arr[st.top()] >= arr[i]) {
                right[st.top()] = i;
                st.pop();
            }
            left[i] = (st.empty() ? -1 : st.top());
            st.push(i);
        }

        int ans = 0;
        for (int i = 0; i < n; ++i) {
            ans = std::max(ans, (right[i] - left[i] - 1) * arr[i]);
        }
        return ans;
}

int maxAreaV2(std::vector<int>& arr) {
        arr.push_back(0);
        int n = arr.size();
        int ans = 0;

        std::stack<int> st;
        for (int i = 0; i < n; ++i) {
            while (!st.empty() && arr[st.top()] > arr[i]) {
                int top = st.top();
                int h = arr[top];
                int w = i - top;
                ans = std::max(ans, h * w);
                st.pop();
                if (st.empty()) {
                    break;
                }
            }
            st.push(i);
        }
        return ans;
}

int main() {
    std::vector<int> arr{ 4, 1, 2, 3, 15, 6};
    int res = maxAreaV2(arr);

    printf("%d\n", res);
    return 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值