1. All Pairs Boundary Scan
Intuition
For each bar i, fix heights[i] as the rectangle height. Expand left as long as heights[j] >= heights[i] and expand right as long as heights[k] >= heights[i]. Calculate area = height * (right - left + 1).
Algorithm
- Step 1: Initialize
maxArea = 0. - Step 2: Loop
ifrom 0 toN - 1withh = heights[i]. - Step 3: Find
left: decrement fromiwhileleft >= 0 && heights[left] >= h. - Step 4: Find
right: increment fromiwhileright < N && heights[right] >= h. - Step 5:
area = h * (right - left - 1). UpdatemaxArea = max(maxArea, area). - Step 6: Return
maxArea.
#include <iostream>#include <vector>#include <algorithm> class Solution {public: int largestRectangleArea(std::vector<int>& heights) { int n = heights.size(); int maxArea = 0; for (int i = 0; i < n; i++) { int h = heights[i]; int left = i; while (left >= 0 && heights[left] >= h) { left--; } int right = i; while (right < n && heights[right] >= h) { right++; } int width = right - left - 1; maxArea = std::max(maxArea, h * width); } return maxArea; }}; int main() { Solution solver; std::vector<int> heights = {2, 1, 5, 6, 2, 3}; std::cout << "Max Area: " << solver.largestRectangleArea(heights) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— For every bar i, scan left to find the left boundary and scan right to find the right boundary. - Space complexity:
O(1)— O(1) extra space.
Why Brute Force Doesn't Scale:
At N = 100,000, O(N2) requires 1010 operations.
Single-pass Monotonic Stack solves N = 100,000 in <15ms.