
Problem
Solution
Submissions
Largest Rectangle in Histogram
Certification: Advanced Level
Accuracy: 40%
Submissions: 5
Points: 12
Write a C++ program to find the largest rectangle in a histogram. Given an array of integers heights representing the histogram's bar heights where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1
- Input: heights = [2, 1, 5, 6, 2, 3]
- Output: 10
- Explanation:
- Step 1: Iterate through each bar in the histogram.
- Step 2: For each bar, calculate the largest rectangle that can include this bar.
- Step 3: The largest rectangle has an area of 10 units, formed by bars at indices 2-3 with height 5.
- Step 4: Return the maximum area found.
Example 2
- Input: heights = [2, 4, 5, 3, 1]
- Output: 9
- Explanation:
- Step 1: Iterate through each bar in the histogram.
- Step 2: For each bar, calculate the largest rectangle that can include this bar.
- Step 3: The largest rectangle has an area of 9 units, formed by bars at indices 1-3 with height 3.
- Step 4: Return the maximum area found.
Constraints
- 1 ≤ heights.length ≤ 10^5
- 0 ≤ heights[i] ≤ 10^4
- Time Complexity: O(n) where n is the number of bars
- 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 bars in non-decreasing order of height
- When you find a bar shorter than the one at the top of the stack, you can calculate areas
- The width of the rectangle is determined by the distance between the current bar and the bar just before the popped bar
- Continue popping bars and calculating areas until you find a shorter bar or the stack is empty
- Remember to process remaining bars in the stack after scanning the entire array