public class Solution
{
public int LargestRectangleArea(int[] hist)
{
// The main function to find the
// maximum rectangular area under
// given histogram with n bars
int n = hist.Length;
// Create an empty stack. The stack
// holds indexes of hist[] array
// The bars stored in stack are always
// in increasing order of their heights.
Stack<int> s = new Stack<int>(); int max_area = ; // Initialize max area
int tp; // To store top of stack
int area_with_top; // To store area with top
// bar as the smallest bar // Run through all bars of
// given histogram
int i = ;
while (i < n)
{
// If this bar is higher than the
// bar on top stack, push it to stack
if (s.Count == || hist[s.Peek()] <= hist[i])
{
s.Push(i++);
} // If this bar is lower than top of stack,
// then calculate area of rectangle with
// stack top as the smallest (or minimum
// height) bar. 'i' is 'right index' for
// the top and element before top in stack
// is 'left index'
else
{
tp = s.Peek(); // store the top index
s.Pop(); // pop the top // Calculate the area with hist[tp]
// stack as smallest bar
area_with_top = hist[tp] *
(s.Count == ? i : i - s.Peek() - ); // update max area, if needed
if (max_area < area_with_top)
{
max_area = area_with_top;
}
}
} // Now pop the remaining bars from
// stack and calculate area with every
// popped bar as the smallest bar
while (s.Count > )
{
tp = s.Peek();
s.Pop();
area_with_top = hist[tp] *
(s.Count == ? i : i - s.Peek() - ); if (max_area < area_with_top)
{
max_area = area_with_top;
}
} return max_area;
}
}

参考:https://www.geeksforgeeks.org/largest-rectangle-under-histogram/

补充一个python的实现:

 class Solution:
def largestRectangleArea(self, heights: 'List[int]') -> int:
heights.append(0)#默认最后补充一个0,方便统一处理
n = len(heights)
s = []
max_area = 0#最大面积
tp = 0#栈顶索引
area_with_top = 0#临时面积
i = 0
while i < n:
if len(s) == 0 or heights[s[-1]] <= heights[i]:
s.append(i)#栈内记录的是高度递增的索引
i += 1
else:#遇到了高度比当前栈顶元素低的元素时,
tp = s.pop(-1)#清算栈内的元素的高度
if len(s) == 0:
area_with_top = heights[tp] * i#栈内没有元素,则宽度是i
else:#高度是栈顶元素,宽度是i - 1 - 前一个栈顶元素的索引
area_with_top = heights[tp] * (i - s[-1] - 1)
max_area = max(max_area,area_with_top)#更新最大值
# while len(s) > 0:#处理栈内剩余元素,处理流程和遇到一个
# tp = s.pop(-1)
# if len(s) == 0:
# area_with_top = heights[tp] * i
# else:
# area_with_top = heights[tp] * (i - s[-1] - 1)
# max_area = max(max_area,area_with_top)
return max_area

采用了一个小技巧,在heights最后补一个0,则21行到27行的代码就可以省略了。

leetcode84的更多相关文章

  1. [Swift]LeetCode84. 柱状图中最大的矩形 | Largest Rectangle in Histogram

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

  2. 【leetcode-84】 柱状图中最大的矩形

    (1pass,比较简单的hard) 给定 n 个非负整数,用来表示柱状图中各个柱子的高度.每个柱子彼此相邻,且宽度为 1 . 求在该柱状图中,能够勾勒出来的矩形的最大面积. 以上是柱状图的示例,其中每 ...

  3. leetcode84 Largest Rectangle in Histogram

    思路: 使用单调栈计算每个位置左边第一个比它矮的位置和右边第一个比它矮的位置即可. 实现: #include <bits/stdc++.h> using namespace std; cl ...

  4. Leetcode84. 柱状图中最大的矩形(单调栈)

    84. 柱状图中最大的矩形 前置 单调栈 做法 连续区间组成的矩形,是看最短的那一块,求出每一块左边第一个小于其高度的位置,右边也同理,此块作为最短限制.需要两次单调栈 单调栈维护递增区间,每次不满足 ...

  5. leetcode84 柱状图

    O(n^2) time 应用heights[r]<=heights[r+1]剪枝: class Solution { public: int largestRectangleArea(vecto ...

  6. LeetCode---84. 柱状图中最大的矩形(hard)

    题目:84. 柱状图中最大的矩形 给定 n 个非负整数,用来表示柱状图中各个柱子的高度.每个柱子彼此相邻,且宽度为 1 . 求在该柱状图中,能够勾勒出来的矩形的最大面积. 示例: 输入: [2,1,5 ...

  7. LeetCode (85): Maximal Rectangle [含84题分析]

    链接: https://leetcode.com/problems/maximal-rectangle/ [描述] Given a 2D binary matrix filled with '0's ...

  8. LeetCode85 Maximal Rectangle java题解

    public static int maximalRectangle(char[][] matrix) { int rowNum=matrix.length; if(rowNum==0) return ...

  9. leetcode 日常清单

    a:excellent几乎一次ac或只有点小bug很快解决:半年后再重刷: b:经过艰难的debug和磕磕绊绊或者看了小提示才刷出来: c:经过艰难的debug没做出来,看答案刷的: 艾宾浩斯遗忘曲线 ...

随机推荐

  1. Angular2 NgModule 模块详解

    原文  https://segmentfault.com/a/1190000007187393 我们今天要学习的是Angular2的模块系统,一般情况下我们使用一个根模块去启动我们的应用,然后使用许多 ...

  2. 解决jmeter乱码

    1. 解决响应数据乱码的方法:     在jemter文件下找到bin\jmeter.properties添加下面一句话:    sampleresult.default.encoding=UTF-8 ...

  3. Oracle 创建存储过程 提示权限不足或者提示表和视图不存在问题

    grant create view to hospital; --授予查询权限 grant select any table to hospital; --授予权限 grant select any ...

  4. groupadd语法

    groupadd [选项] 组 创建一个新的组.Groupadd命令使用命令行中指定的值加上系统默认值创建新的组账户.新组将根据需要输入系统. (1).选项 1 2 3 4 5 6 7 -f,--fo ...

  5. python 写的员工信息查询

    #!/use/bin/env pythonn#_*_ coding:utf-8 _*_import timedef Bre():    while True:        Bre_falg = ra ...

  6. Gram格拉姆矩阵在风格迁移中的应用

    Gram定义 n维欧式空间中任意k个向量之间两两的内积所组成的矩阵,称为这k个向量的格拉姆矩阵(Gram matrix) 根据定义可以看到,每个Gram矩阵背后都有一组向量,Gram矩阵就是由这一组向 ...

  7. jsonify

    在flask中通过响应,将json数据显示在网页中,并且将Content-Type该为application/json格式 1,第一种方法: from flask import jsonify @ap ...

  8. Spring @Resource,@Autowired,@Qualifier的注解注入和区别

    spring2.5提供了基于注解(Annotation-based)的配置,我们可以通过注解的方式来完成注入依赖.在Java代码中可以使用 @Resource或者@Autowired注解方式来经行注入 ...

  9. OneStopEnglish corpus: A new corpus for automatic readability assessment and text simplification-paper

    这篇论文的related work非常详尽地介绍了各种readability的语料 abstract这个paper描述了onestopengilish这个三个level的文本语料的收集和整理,阐述了再 ...

  10. 常见模块(二) logging模块

    logging模块是专门做日志系统的.分为函数版和自定义函数. (一)logging模块初级版 缺点,不能指定字符集,不能把屏幕输出和文件日志同时记录.只能选择其一. 文件记录日志 import lo ...