1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_84.java 1.23 KB
一键复制 编辑 原始数据 按行查看 历史
Fisher Coder 提交于 2019-12-18 23:10 +08:00 . refactor 84
package com.fishercoder.solutions;
import java.util.Stack;
/**
* 84. Largest Rectangle in Histogram
*
* 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.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
*/
public class _84 {
public static class Solution1 {
/**
* credit: https://leetcode.com/articles/largest-rectangle-histogram/#approach-5-using-stack-accepted
* and https://discuss.leetcode.com/topic/7599/o-n-stack-based-java-solution
*/
public int largestRectangleArea(int[] heights) {
int len = heights.length;
Stack<Integer> s = new Stack<>();
int maxArea = 0;
for (int i = 0; i <= len; i++) {
int h = (i == len ? 0 : heights[i]);
if (s.isEmpty() || h >= heights[s.peek()]) {
s.push(i);
} else {
int tp = s.pop();
maxArea = Math.max(maxArea, heights[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助