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

参考博客

相关推荐
Ronin305几秒前
虚拟机数据管理模块
开发语言·c++·rabbitmq
熬了夜的程序员1 分钟前
【LeetCode】117. 填充每个节点的下一个右侧节点指针 II
java·算法·leetcode
wengqidaifeng1 分钟前
数据结构---链表的奇特(下)双向链表的多样魅力
c语言·数据结构·链表
一叶之秋141214 分钟前
基石之力:掌握 C++ 继承的核心奥秘
开发语言·c++·算法
见牛羊15 分钟前
CMakeLists 写法总结3.0
开发语言·c++
柒儿吖16 分钟前
rudp Reliable UDP 库在 OpenHarmony 的 lycium 适配与 CRC32 测试
c++·c#·openharmony
拾光Ծ17 分钟前
【优选算法】滑动窗口算法:专题一
c++·算法·滑动窗口·c++算法·滑动窗口算法·笔试面试
im_AMBER22 分钟前
Leetcode 118 从中序与后序遍历序列构造二叉树 | 二叉树的最大深度
数据结构·学习·算法·leetcode
YuTaoShao22 分钟前
【LeetCode 每日一题】3721. 最长平衡子数组 II ——(解法二)分块
java·算法·leetcode
Faker66363aaa22 分钟前
YOLOv10n改进实现CFPT-P23456算法——压力容器管道表面轻微锈蚀检测
算法·yolo·计算机视觉