
Problem
Solution
Submissions
Largest Rectangle in Histogram
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C# program to implement the LargestRectangleArea(int[] heights)
function, which calculates the area of the largest rectangle in a histogram where the width of each bar is 1.
Example 1
- Input: heights = [2, 1, 5, 6, 2, 3]
- Output: 10
- Explanation:
- Step 1: Analyze each bar and calculate the maximum rectangle that can extend from it.
- Step 2: For each bar, find how far it can extend to the left and right while maintaining its height.
- At position 2 (height 5), it can extend to position 3 (height 6).
- This forms a rectangle of height 5 and width 2.
- The area of this rectangle is 5 × 2 = 10.
- Step 3: Compare all possible rectangle areas to find the maximum.
- Step 4: Return the maximum area, which is 10.
Example 2
- Input: heights = [2, 4]
- Output: 4
- Explanation:
- Step 1: Analyze each bar and calculate the maximum rectangle that can extend from it.
- Step 2: For each bar, find how far it can extend to the left and right while maintaining its height.
- At position 0 (height 2), it can extend across both bars.
- This forms a rectangle of height 2 and width 2.
- The area of this rectangle is 2 × 2 = 4.
- At position 1 (height 4), it can only include itself.
- This forms a rectangle of height 4 and width 1.
- The area of this rectangle is 4 × 1 = 4.
- Step 3: Compare all possible rectangle areas to find the maximum.
- Step 4: Return the maximum area, which is 4.
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) for the stack used in the algorithm
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
- When a shorter bar is found, pop from the stack and calculate areas
- Consider using a sentinel value at the end of the array to simplify the algorithm
- For each bar, the area can be calculated as height × width