Leetcode 84. Largest Rectangle in Histogram

本文介绍了两种计算直方图中最大矩形面积的算法:一种是O(N^2)的时间复杂度,通过遍历每个柱子并计算可能的最大面积;另一种是O(N)的时间复杂度,使用栈来优化计算过程,提高效率。文章提供了详细的代码实现,并附有参考链接。

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

1. Description

Largest Rectangle in Histogram

2. Solution

  • O(N^2)
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int maxArea = 0;
        for(int i = 0; i < heights.size(); i++) {
            int left = i;
            int right = i;
            for(left = i; left >= 0; left--) {
                if(heights[left] < heights[i]) {
                    break;
                }
            }
            for(right = i; right < heights.size(); right++) {
                if(heights[right] < heights[i]) {
                    break;
                }
            }
            int area = (right - 1 - left - 1 + 1) * heights[i];
            if(area > maxArea) {
                maxArea = area;
            }
        }
        return maxArea;
    }
};
  • O(N)
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int maxArea = 0;
        stack<int> border;
        heights.push_back(0);
        for(int i = 0; i < heights.size(); i++) {
            if(border.empty() || heights[i] > heights[border.top()]) {
                border.push(i);
            }
            else {
                int index = border.top();
                border.pop();
                int area = heights[index] * (border.empty()?i:i - border.top() - 1);
                if(area > maxArea) {
                    maxArea = area;
                }
                i--;
            }
        }
        return maxArea;
    }
};

Reference

  1. https://leetcode.com/problems/largest-rectangle-in-histogram/description/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值