Intuition
For each bar, expand left and right to find the widest rectangle that uses this bar's height as the limiting height.
Explanation
Brute Force
For each bar at index i, treat heights[i] as the rectangle's height. Expand leftward while bars are at least as tall, then expand rightward. The width is (right - left + 1). Track the maximum area across all bars.
This requires O(n) expansion per bar, giving O(n²) time overall. Space is O(1).
Why it's slow: every bar re-scans its neighbours, leading to redundant comparisons.
Implementation
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int maxArea = 0;
for (int i = 0; i < n; i++) {
int h = heights[i];
int left = i;
int right = i;
while (left > 0 && heights[left - 1] >= h) {
left--;
}
while (right < n - 1 && heights[right + 1] >= h) {
right++;
}
int area = h * (right - left + 1);
maxArea = Math.max(maxArea, area);
}
return maxArea;
}
}