Beats 99%✅  |  O( n )✅  |  Python (Step by step explanation)
Intuition\nThe problem involves finding the largest rectangle that can be formed in a histogram of different heights. The approach is to iteratively process the
# Intuition\nThe problem involves finding the largest rectangle that can be formed in a histogram of different heights. The approach is to iteratively process the histogram\'s bars while keeping track of the maximum area found so far.\n\n# Approach\n1. Initialize a variable `maxArea` to store the maximum area found, and a stack to keep track of the indices and heights of the histogram bars.\n\n2. Iterate through the histogram using an enumeration to access both the index and height of each bar.\n\n3. For each bar, calculate the width of the potential rectangle by subtracting the starting index (retrieved from the stack) from the current index.\n\n4. While the stack is not empty and the height of the current bar is less than the height of the bar at the top of the stack, pop elements from the stack to calculate the area of rectangles that can be formed.\n\n5. Update `maxArea` with the maximum of its current value and the area calculated in step 4.\n\n6. Push the current bar\'s index and height onto the stack to continue processing.\n\n7. After processing all bars, there may still be bars left in the stack. For each remaining bar in the stack, calculate the area using the height of the bar and the difference between the current index and the index at the top of the stack.\n\n8. Return `maxArea` as the result, which represents the largest rectangle area.\n\n# Complexity\n- Time complexity: O(n), where n is the number of bars in the histogram. We process each bar once.\n- Space complexity: O(n), as the stack can contain up to n elements in the worst case when the bars are in increasing order (monotonic).\n\n\n# Code\n```\nclass Solution:\n    def largestRectangleArea(self, heights: List[int]) -> int:\n        maxArea = 0\n        stack = []\n\n        for index , height in enumerate(heights):\n            start = index\n            \n            while start and stack[-1][1] > height:\n                i , h = stack.pop()\n                maxArea = max(maxArea , (index-i)*h)\n                start = i\n            stack.append((start , height))\n\n        for index , height in stack:\n            maxArea = max(maxArea , (len(heights)-index)*height)\n\n        return maxArea    \n\n                \n\n\n        \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/a424b536-ba47-4657-92ab-72117d85a927_1697476020.1517317.jpeg)\n
['Stack', 'Python3']