
Problem
Solution
Submissions
Largest Rectangle in Histogram
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the area of the largest rectangle that can be formed in a histogram. Given an array of integers representing the heights of bars in a histogram where the width of each bar is 1, find the area of the largest rectangle that can be formed within the bounds of the histogram.
Example 1
- Input: heights = [2,1,5,6,2,3]
- Output: 10
- Explanation:
- The largest rectangle can be formed using bars at indices 2 and 3 with heights 5 and 6.
- The minimum height between these bars is 5.
- Rectangle area = min_height * width = 5 * 2 = 10.
- Therefore, the largest rectangle area is 10.
- The largest rectangle can be formed using bars at indices 2 and 3 with heights 5 and 6.
Example 2
- Input: heights = [2,4]
- Output: 4
- Explanation:
- We can form rectangles of area 2*2=4 using the second bar, or 2*1=2 using the first bar.
- The largest rectangle uses the bar of height 4 with width 1.
- Rectangle area = 4 * 1 = 4.
- Therefore, the largest rectangle area is 4.
- We can form rectangles of area 2*2=4 using the second bar, or 2*1=2 using the first bar.
Constraints
- 1 ≤ heights.length ≤ 10^5
- 0 ≤ heights[i] ≤ 10^4
- Time Complexity: O(n)
- 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 indices of histogram bars
- For each bar, if it's higher than the bar at the top of stack, push its index
- If current bar is lower, pop from stack and calculate area with popped bar as the smallest
- The width is determined by the current index and the index after the new top of stack
- Continue until all bars are processed and stack is empty
- Keep track of the maximum area found during the process