Finding the largest rectangular area in a histogram.
Here’s an example of a Java program that finds the largest rectangular area in a histogram:
import java.util.Stack; public class LargestRectangularArea { public static int findLargestRectangularArea(int[] heights) { Stack<Integer> stack = new Stack<>(); int maxArea = 0; int i = 0; while (i < heights.length) { if (stack.isEmpty() || heights[i] >= heights[stack.peek()]) { stack.push(i); i++; } else { int top = stack.pop(); int area = heights[top] * (stack.isEmpty() ? i : i - stack.peek() - 1); maxArea = Math.max(maxArea, area); } } while (!stack.isEmpty()) { int top = stack.pop(); int area = heights[top] * (stack.isEmpty() ? i : i - stack.peek() - 1); maxArea = Math.max(maxArea, area); } return maxArea; } public static void main(String[] args) { int[] heights = {2, 1, 5, 6, 2, 3}; int largestArea = findLargestRectangularArea(heights); System.out.println("The largest rectangular area in the histogram is: " + largestArea); } }
In this program, the `findLargestRectangularArea` method takes an array of `heights` representing the heights of bars in a histogram. It uses a stack to keep track of the indices of the bars in non-decreasing order of heights. The algorithm iterates over the heights and pushes the indices to the stack as long as the current height is greater than or equal to the height at the top of the stack. If the current height is smaller, it pops the indices from the stack and calculates the area of the rectangle formed by the popped bar. The width of the rectangle is determined by the difference between the current index and the index at the top of the stack. The maximum area is updated whenever a larger area is found.
In the `main` method, we create an example array of heights, call the `findLargestRectangularArea` method, and print the result. In this case, the largest rectangular area in the histogram with heights [2, 1, 5, 6, 2, 3] is 10.