Description:
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
.
Solution:
We can solve this problem in two ways, DP or one deque. And I would like to show the second solution here.
Suppose we want to maintain a deque h[]. And here we how to maintain this deque.
Then we began our loop, for each element in this height array:
if the deque is empty or the top value of the deque is less than new element, then we pop up the first element, and then calculate the area of this pop-up element with its former one or if no former one, calculate its area with the first one.
if the new element is greater than or equal to the top element, then just push this new element into this deque.
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args){
Solution s = new Solution();
int arr[]={1,2,3};
System.out.println(s.largestRectangleArea(arr));
}
public int largestRectangleArea(int[] height) {
if(height==null)
return 0;
int n = height.length;
int h[] = new int[n+1];
h = Arrays.copyOf(height, n+1);
int max=0;
Stack<Integer> stack = new Stack<Integer>();
int i =0;
while(i<=n){
if(stack.isEmpty()||h[stack.peek()]<h[i]){
stack.push(i);
i++;
}else{
int t = stack.pop();
int ta;
if (stack.isEmpty())
ta = i * h[t];
else
ta = (i - stack.peek() - 1) * h[t];
max = Math.max(max, ta);
}
}
return max;
}
}