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 天前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发1 天前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
小镇敲码人1 天前
探索CANN框架中TBE仓库:张量加速引擎的优化之道
c++·华为·acl·cann·ops-nn
wWYy.1 天前
数组快排 链表归并
数据结构·链表
张登杰踩1 天前
MCR ALS 多元曲线分辨算法详解
算法
平安的平安1 天前
面向大模型算子开发的高效编程范式PyPTO深度解析
c++·mfc
June`1 天前
muduo项目排查错误+测试
linux·c++·github·muduo网络库
C++ 老炮儿的技术栈1 天前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
YuTaoShao1 天前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
Once_day1 天前
C++之《Effective C++》读书总结(4)
c语言·c++·effective c++