标签:keep dia his empty hose alt represent math about
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.
Given height = [2,1,5,6,2,3]
,
return 10
.
1 public class Solution { 2 public int largestRectangleArea(int[] height) { 3 if(height == null || height.length == 0){ 4 return 0; 5 } 6 Stack<Integer> idxStack = new Stack<Integer>(); 7 int currIdx = 0; int area = 0; int maxArea = 0; 8 while(currIdx < height.length){ 9 if(idxStack.isEmpty() || height[currIdx] >= height[idxStack.peek()]){ 10 idxStack.push(currIdx); 11 currIdx++; 12 } 13 else{ 14 int top = idxStack.pop(); 15 int leftBoundIdx = idxStack.isEmpty() == true ? -1 : idxStack.peek(); 16 int rightBoundIdx = currIdx - 1; 17 area = height[top] * (rightBoundIdx - leftBoundIdx); 18 maxArea = Math.max(maxArea, area); 19 } 20 } 21 while(!idxStack.isEmpty()){ 22 int top = idxStack.pop(); 23 int leftBoundIdx = idxStack.isEmpty() == true ? -1 : idxStack.peek(); 24 int rightBoundIdx = currIdx - 1; 25 area = height[top] * (rightBoundIdx - leftBoundIdx); 26 maxArea = Math.max(maxArea, area); 27 } 28 return maxArea; 29 } 30 }
[LintCode] Largest Rectangle in Histogram
标签:keep dia his empty hose alt represent math about
原文地址:http://www.cnblogs.com/lz87/p/7477789.html