
Problem
Solution
Submissions
Largest Rectangle in Histogram
Certification: Advanced Level
Accuracy: 50%
Submissions: 2
Points: 15
Write a Java program to find the largest rectangle area in a histogram. A histogram is represented as an array of integers where each element represents the height of the bar at that position. The width of each bar is 1.
Example 1
- Input: heights = [2, 1, 5, 6, 2, 3]
- Output: 10
- Explanation: The maximum area can be formed by heights[2] = heights[3] = 5 with width 2. Area = 5 * 2 = 10.
Example 2
- Input: heights = [2, 4, 5, 3, 1]
- Output: 9
- Explanation: For heights[3] = 3, we can extend the width to 3, creating an area of 3 * 3 = 9.
Constraints
- 1 <= heights.length <= 10^5
- 0 <= heights[i] <= 10^4
- Time Complexity: O(n), where n is the length of the heights array
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a stack to keep track of increasing heights in the histogram
- When you find a bar shorter than the top of the stack, you've found a right boundary
- Pop from the stack to get the height of the rectangle
- The width will be the current position minus the new top of the stack minus 1
- For each popped element, calculate the area and keep track of the maximum area
- Process a sentinel value at the end to handle remaining elements in the stack
- Take special care with empty stack cases