Largest Rectangle in Histogram

Intuition

The 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.

Approach

  1. 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.

  2. Iterate through the histogram using an enumeration to access both the index and height of each bar.

  3. For each bar, calculate the width of the potential rectangle by subtracting the starting index (retrieved from the stack) from the current index.

  4. 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.

  5. Update maxArea with the maximum of its current value and the area calculated in step 4.

  6. Push the current bar's index and height onto the stack to continue processing.

  7. 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.

  8. Return maxArea as the result, which represents the largest rectangle area.

Complexity

  • Time complexity: O(n), where n is the number of bars in the histogram. We process each bar once.
  • 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).

Code

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        maxArea = 0
        stack = []

        for index , height in enumerate(heights):
            start = index
            
            while start and stack[-1][1] > height:
                i , h = stack.pop()
                maxArea = max(maxArea , (index-i)*h)
                start = i
            stack.append((start , height))

        for index , height in stack:
            maxArea = max(maxArea , (len(heights)-index)*height)

        return maxArea    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值