Created
October 20, 2013 23:04
-
-
Save charlespunk/7076440 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
// O(n) using two stacks | |
public int largestRectangleArea(int[] height) { | |
int area = 0; | |
Stack<Integer> heightStack = new Stack<Integer>(); | |
Stack<Integer> indexStack = new 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment