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;
}

参考博客

相关推荐
努力写代码的熊大9 分钟前
链式二叉树数据结构(递归)
数据结构
yi.Ist10 分钟前
数据结构 —— 键值对 map
数据结构·算法
爱学习的小邓同学10 分钟前
数据结构 --- 队列
c语言·数据结构
s1533513 分钟前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
闻缺陷则喜何志丹14 分钟前
【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
数据结构·c++·前缀和·宽度优先·洛谷·并集查找
Coding小公仔15 分钟前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七21 分钟前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
DoraBigHead1 小时前
小哆啦解题记——异位词界的社交网络
算法
序属秋秋秋1 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归