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

Leetcode-Largest Rectangle in Histogram

时间:2014-12-16 08:40:59      阅读:224      评论:0      收藏:0      [点我收藏+]

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

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.

Have you met this question in a real interview?
 
Solution:
 1 public class Solution {
 2     public int largestRectangleArea(int[] height) {
 3         if (height.length==0) return 0;
 4 
 5         Stack<Integer> index = new Stack<Integer>();
 6         index.push(-1);
 7         int max = 0;
 8         for (int i=0;i<height.length;i++){
 9             while (index.peek()!=-1){
10                 if (height[index.peek()]>height[i]){
11                     int cur = index.pop();
12                     max = Math.max(max,height[cur]*(i-index.peek()-1));
13                 } else break;
14             }
15             index.push(i);
16         }
17 
18         while (index.peek()!=-1){
19             int cur = index.pop();
20             max = Math.max(max,height[cur]*(height.length-index.peek()-1));
21         }
22 
23         return max;
24     }    
25        
26 }

 

Leetcode-Largest Rectangle in Histogram

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

原文地址:http://www.cnblogs.com/lishiblog/p/4166268.html

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