2 Star 10 Fork 2

国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_84.java 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
package com.hit.basmath.learn.recursion_ii;
/**
* 84. Largest Rectangle in Histogram
* <p>
* Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
* <p>
* Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
* <p>
* The largest rectangle is shown in the shaded area, which has area = 10 unit.
* <p>
* Example:
* <p>
* Input: [2,1,5,6,2,3]
* Output: 10
*/
public class _84 {
public int largestRectangleArea(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
// idx of the first bar the left that is lower than current
int[] lessFromLeft = new int[height.length];
// idx of the first bar the right that is lower than current
int[] lessFromRight = new int[height.length];
lessFromRight[height.length - 1] = height.length;
lessFromLeft[0] = -1;
for (int i = 1; i < height.length; i++) {
int p = i - 1;
while (p >= 0 && height[p] >= height[i]) {
p = lessFromLeft[p];
}
lessFromLeft[i] = p;
}
for (int i = height.length - 2; i >= 0; i--) {
int p = i + 1;
while (p < height.length && height[p] >= height[i]) {
p = lessFromRight[p];
}
lessFromRight[i] = p;
}
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
}
return maxArea;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助