acwing-3194 最大的矩形

acwing-3194 最大的矩形

这个题程序设计课上有讲过,

平民算法,时间复杂度在 O ( n 2 ) O(n^2) O(n2)

C++ 复制代码
//
// Created by HUAWEI on 2024/10/28.
//
#include<iostream>

using namespace std;

const int Max_size = 1e4 + 20;

int N;
int h[Max_size];

int main() {
    cin >> N;
    for (int i = 0; i < N; i++)
        cin >> h[i];
    int res = 0;
    for (int i = 0; i < N; i++) {
        int l = i - 1;
        int r = i + 1;
        while (l >= 0 and h[l] >= h[i])l--;
        while (r <= N - 1 and h[r] >= h[i])r++;
        int temp = (r - l - 1) * h[i];
        if (temp > res)
            res = temp;

    }
    cout << res << endl;
    return 0;
}

单调栈解决,时间复杂度在 O ( n ) O(n) O(n)

C++ 复制代码
//
// Created by HUAWEI on 2024/10/28.
//
#include<iostream>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>

using namespace std;

int largestArea(vector<int> &h) {
    // 单调栈返回最大矩形面积
    stack<int> s; //单调非减栈
    h.insert(h.begin(), -1);
    h.push_back(0);
    int len = h.size();
    int res = 0;
    s.push(0);
    for (int i = 1; i < len; i++) {
        while (h[i] < h[s.top()]) {
            int temp = s.top();
            s.pop();
            res = max(res, (h[temp] * (i - s.top() - 1)));
        }
        s.push(i);
    }
    return res;
}

int main() {
    int n;
    vector<int> h;
    cin >> n;
    for (int i = 0; i < n; i++) {
        int temp;
        cin >> temp;
        h.push_back(temp);
    }
    cout << largestArea(h);

    return 0;
}

参考博客

相关推荐
青草地溪水旁1 分钟前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁8 分钟前
UML函数原型中guard的含义,有啥用?
c++·uml
百度Geek说39 分钟前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven1 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven1 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试
CoovallyAIHub1 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·计算机视觉
kyle~2 小时前
OpenCV---特征检测算法(ORB,Oriented FAST and Rotated BRIEF)
人工智能·opencv·算法
初学小刘2 小时前
决策树:机器学习中的强大工具
算法·决策树·机器学习
山顶风景独好2 小时前
【Leetcode】随笔
数据结构·算法·leetcode
光头闪亮亮3 小时前
C++凡人修仙法典 - 宗门版-上
c++