
using System;
using System.Collections.Generic;
public class Solution
{
public int LargestRectangleArea(int[] heights)
{
int maxArea = 0;
Stack stack = new Stack(); // Stores indices of bars
for (int i = 0; i <= heights.Length; i++)
{
// Get current height (or 0 if at the end to process remaining stack elements)
int currentHeight = (i == heights.Length) ? 0 : heights[i];
// While the stack is not empty and the current height is less than
// or equal to the height of the bar at the top of the stack
while (stack.Count > 0 && currentHeight <= heights[stack.Peek()])
{
int h = heights[stack.Pop()]; // Height of the popped bar
int w = stack.Count == 0 ? i : i - stack.Peek() - 1; // Width of the rectangle
maxArea = Math.Max(maxArea, h * w); // Update maxArea
}
stack.Push(i); // Push the current bar's index onto the stack
}
return maxArea;
}
}