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.
publicintlargestRectangleArea(int[] heights){ Set<Integer> set = new HashSet<>(); for (int height : heights) { set.add(height); } int res = 0; for (int height : set) { int width = 0; int max = 1; for (int value : heights) { if (value >= height) { width++; } else { max = Math.max(max, width); width = 0; } } max = Math.max(max, width); res = Math.max(res, max * (height)); } return res; }
publicintlargestRectangleArea(int[] heights){ int max = 0; Stack<Integer> stack = new Stack<>(); int i = 0; while (i < heights.length) { if (stack.isEmpty()) { stack.push(i); i++; } else { int peek = stack.peek(); if (heights[i] >= heights[peek]) { stack.push(i); i++; } else { int height = heights[stack.pop()]; int leftMin = stack.isEmpty() ? -1 : stack.peek(); int area = (i - leftMin - 1) * height; max = Math.max(area, max); } } }
while (!stack.isEmpty()) { int height = heights[stack.pop()]; int leftMin = stack.isEmpty() ? -1 : stack.peek(); int area = (heights.length - leftMin - 1) * height; max = Math.max(area, max); } return max; }