Largest Rectangle in Histogram
2015-08-07 13:47
453 查看
Largest Rectangle in Histogram
Total Accepted: 18582 TotalSubmissions: 86792My Submissions
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 =
10unit.
For example,
Given height =
[2,1,5,6,2,3],
return
10.
Have you been asked this question in an interview?
public class Solution { public int largestRectangleArea(int[] height) { int [] leftSmall = new int[height.length]; int [] rightSmall = new int[height.length]; Stack<PositionNode> smallStack = new Stack<PositionNode>(); for (int i = 0; i < height.length; i++) { while (!smallStack.isEmpty() && smallStack.peek().height >= height[i]){ smallStack.pop(); } if (!smallStack.isEmpty()) { leftSmall[i] = smallStack.peek().pos; } else { leftSmall[i] = -1; } smallStack.push(new PositionNode(i,height[i])); } smallStack.clear(); for (int i = height.length - 1; i > -1; i--) { while (!smallStack.isEmpty() && smallStack.peek().height >= height[i]){ smallStack.pop(); } if (!smallStack.isEmpty()) { rightSmall[i] = smallStack.peek().pos; } else { rightSmall[i] = height.length ; } PositionNode newNode = new PositionNode(i,height[i]); smallStack.push(newNode); } int maxArea = 0; for (int i = 0; i < height.length; i++) { int thisArea = height[i] * Math.abs(rightSmall[i] - leftSmall[i] - 1); maxArea = Math.max(maxArea,thisArea); } return maxArea; } class PositionNode { int pos; int height; public PositionNode(int pos, int height) { this.pos = pos; this.height = height; } } }
相关文章推荐
- Codeforces 540 E. Infinite Inversions
- REST风格的API
- Android NDK学习 <二> Android.mk的制作
- 视频叠加字幕显示原理与实现方法
- .NET PDF转图片
- *Delphi控件之---通过编码学习TStringGrid(也会涉及到Panel控件,还有对Object Inspector的控件Events的介绍
- fsck
- Android点击跳转到联系人列表、拨号面板和通话记录
- 杭电1061 Rightmost Digit
- MapReduce框架Mapper和Reducer类源码分析
- scp命令
- iOS设计模式简介
- docker 环境下ambari-2.1.0离线升级hdp2.2.6.0 to hdp2.3.0.0
- 黑马程序员---OC基础---Foundation(上)
- HDU 2931 Digit Puzzle 搜索 DFS
- FatSecret Platform API
- Best Time to Buy and Sell Stock III
- spring mvc 配置 Mabatis 模板
- httpclient httpget接口小demo
- 使用MAT(Memory Analyzer Tool)分析内存泄漏