Chinaunix首页 | 论坛 | 博客
  • 博客访问: 270020
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-09-19 10:49:29

//Largest Rectangle in Histogram My Submissions Question Solution 
//Total Accepted: 44118 Total Submissions: 193905 Difficulty: Hard
//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 height = [2,1,5,6,2,3],
//return 10.
public class LargestRectangleinHistogram {


public static void main(String[] args) {
// TODO Auto-generated method stub


}
public int largestRectangleArea(int[] height) {
    int area = 0;  
 java.util.Stack<Integer> heightStack = new java.util.Stack<Integer>();  
 java.util.Stack<Integer> indexStack = new java.util.Stack<Integer>();  
 for (int i = 0; i < height.length; i++) {  
   if (heightStack.empty() || heightStack.peek() <= height[i]) {  
     heightStack.push(height[i]);  
     indexStack.push(i);  
   } else if (heightStack.peek() > height[i]) {  
     int j = 0;  
     while (!heightStack.empty() && heightStack.peek() > height[i]) {  
       j = indexStack.pop();  
       int currArea = (i - j) * heightStack.pop();  
       if (currArea > area) {  
         area = currArea;  
       }  
     }  
     heightStack.push(height[i]);  
     indexStack.push(j);  
   }  
 }  
 while (!heightStack.empty()) {  
   int currArea = (height.length - indexStack.pop()) * heightStack.pop();  
   if (currArea > area) {  
     area = currArea;  
   }  
 }  
 return area;  
   }


}

阅读(378) | 评论(0) | 转发(0) |
0

上一篇:MaximalRectangle

下一篇:PartitionList

给主人留下些什么吧!~~