Imagine you're looking at a histogram - a bar chart where each bar has a height and width of 1 unit. Your task is to find the largest rectangle that can be formed within this histogram.
Given an array heights where heights[i] represents the height of the i-th bar, you need to calculate the maximum area of any rectangle that can be formed using one or more consecutive bars.
The key insight is that a rectangle's height is limited by the shortest bar it contains, but it can extend horizontally as far as possible while maintaining that minimum height.
Example: For heights [2,1,5,6,2,3], the largest rectangle has area 10 (height=5, width=2, using bars at indices 2 and 3).
Input & Output
Visualization
Time & Space Complexity
Each bar is pushed and popped from stack at most once, giving us linear time
Stack can contain up to n elements in worst case (strictly increasing heights)
Constraints
- 1 โค heights.length โค 105
- 0 โค heights[i] โค 104
- All heights are non-negative integers