Hard
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.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
1 <= heights.length <= 105
0 <= heights[i] <= 104
To solve this task using Python with a Solution
class, you can follow these steps:
Solution
.largestRectangleArea
that takes heights
as an input parameter.Here’s the implementation:
class Solution:
def largestRectangleArea(self, heights):
max_area = 0
stack = []
heights.append(0) # Append 0 to the end to handle the case when all bars are ascending
for i in range(len(heights)):
while stack and heights[i] < heights[stack[-1]]:
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
# Example usage:
solution = Solution()
print(solution.largestRectangleArea([2,1,5,6,2,3])) # Output: 10
print(solution.largestRectangleArea([2,4])) # Output: 4
This solution efficiently finds the largest rectangle area in the histogram using a stack-based approach. It iterates through the histogram only once, resulting in a time complexity of O(n), where n is the number of bars in the histogram.
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
lefts = [0]
best = 0
heights.append(0)
for i,h in enumerate(heights):
if h > heights[lefts[-1]]:
lefts.append(i)
elif h == heights[lefts[-1]]:
pass
elif h < heights[lefts[-1]]:
while lefts and h < heights[lefts[-1]]:
left = lefts.pop()
hh = heights[left]
ww = i - left
if hh * ww > best:
best = hh * ww
lefts.append(left)
heights[left] = h
return best