iT邦幫忙

2022 iThome 鐵人賽

DAY 27
0
自我挑戰組

LeetCode Top 100 Liked系列 第 27

[Day 27] Largest Rectangle in Histogram (Hard)

  • 分享至 

  • xImage
  •  

84. Largest Rectangle in Histogram

Question

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Example 1

Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.

Solution 1: Brute-Force (TLE)

Time Complexity: O(N^3)
Space Complexity: O(1)

Solution 2: Pruning Brute-Force

Time Complexity: O(N^2)
Space Complexity: O(1)

Solution 3: Stack

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        ans = 0
        heights.append(0) # dummy tail 0
        stack = []        # Store the index of local maximum
        for idx in range(len(heights)):
            while stack and heights[stack[-1]] >= heights[idx]:
                idxOfLocalMax = stack.pop()
                width = (idx - stack[-1] - 1) if stack else idx
                ans = max(ans, heights[idxOfLocalMax] * width) 
            stack.append(idx)
        return ans

Time Complexity: O(N^2)
Space Complexity: O(N)

Reference

https://www.cnblogs.com/grandyang/p/4322653.html
https://medium.com/hoskiss-stand/largest-rectangle-b3a7473320c1


上一篇
[Day 26] Symmetric Tree (Easy)
下一篇
[Day 28] Combination Sum (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言