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 分钟前
【modbus学习】
java·c语言·c++·学习·算法·c#
索迪迈科技3 分钟前
STL库——map/set(类函数学习)
开发语言·c++·学习
Dfreedom.9 分钟前
在Windows上搭建GPU版本PyTorch运行环境的详细步骤
c++·人工智能·pytorch·python·深度学习
Boop_wu15 分钟前
[数据结构] LinkedList
数据结构
兴科Sinco27 分钟前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
沐怡旸28 分钟前
【算法--链表】138.随机链表的复制--通俗讲解
算法·面试
anlogic34 分钟前
Java基础 9.10
java·开发语言·算法
薛定谔的算法37 分钟前
JavaScript单链表实现详解:从基础到实践
数据结构·算法·leetcode
CoovallyAIHub1 小时前
CostFilter-AD:用“匹配代价过滤”刷新工业质检异常检测新高度! (附论文和源码)
深度学习·算法·计算机视觉
幻奏岚音1 小时前
《数据库系统概论》第一章 初识数据库
数据库·算法·oracle