码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Largest Rectangle in Histogram

时间:2014-11-23 17:19:58      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

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.

bubuko.com,布布扣

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

 

bubuko.com,布布扣

The largest rectangle is shown in the shaded area, which has area = 10 unit.

 

For example,
Given height = [2,1,5,6,2,3],
return 10.

 

Solution:

http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

这个大哥讲得太清楚了!!120个赞啊!!!

 1 public class Solution {
 2     public int largestRectangleArea(int[] height) {
 3         if(height==null)
 4             return 0;
 5         int[] h=new int[height.length+1];
 6         h=Arrays.copyOf(height, height.length+1);
 7         Stack<Integer> stack=new Stack<Integer>();
 8         int i=0;
 9         int maxArea=0;
10         while(i<h.length){
11             if(stack.size()==0||h[stack.peek()]<=h[i]){
12                 stack.push(i++);
13             }else{
14                 int t=stack.pop();
15                 maxArea=Math.max(maxArea, h[t]*(stack.isEmpty()?i:i-stack.peek()-1));
16             }
17         }
18         return maxArea;
19     }
20 }

 

[Leetcode] Largest Rectangle in Histogram

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/Phoebe815/p/4116696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!