Largest Rectangle

  • + 0 comments
    #!/bin/python3
    
    import os
    import sys
    
    def largestRectangle(heights):
        stack = []
        max_area = 0
        heights.append(0)  # Sentinel value to flush the stack at the end
    
        for i, h in enumerate(heights):
            while stack and heights[stack[-1]] > h:
                height = heights[stack.pop()]
                width = i if not stack else (i - stack[-1] - 1)
                max_area = max(max_area, height * width)
            stack.append(i)
    
        return max_area
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input())
        h = list(map(int, input().rstrip().split()))
    
        result = largestRectangle(h)
    
        fptr.write(str(result) + '\n')
        fptr.close()