Skip to content

Instantly share code, notes, and snippets.

@yokolet
Last active June 19, 2017 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/9913edf20b07f56eadd44ecc574d3c78 to your computer and use it in GitHub Desktop.
Save yokolet/9913edf20b07f56eadd44ecc574d3c78 to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class LargestRectangleInHistogram {
static int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
int n = heights.length;
Stack<Integer> stack = new Stack<Integer>();
int max_area = 0;
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) {
int top_height = heights[stack.pop()];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max_area = Math.max(max_area, w * top_height);
}
stack.push(i);
}
while (!stack.isEmpty()) {
int top_height = heights[stack.pop()];
int w = stack.isEmpty() ? n : n - stack.peek() - 1;
max_area = Math.max(max_area, w * top_height);
}
return max_area;
}
public static void main(String[] args) {
int[] nums0 = {6, 2, 5, 4, 5, 1, 6};
System.out.println(largestRectangleArea(nums0));
int[] nums1 = {6, 2, 5, 4, 5, 2, 6};
System.out.println(largestRectangleArea(nums1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment