[LeetCode][Python3] 84. Largest Rectangle in Histogram
2019. 4. 15. 01:13 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/largest-rectangle-in-histogram/
My Solution :
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0)
stack = [-1]
area = 0
for i, height in enumerate(heights):
while height < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
area = max(area, h*w)
stack.append(i)
return area
Comment :
원래 FM대로 하면 아래와 같이 코드가 길어야 하는데, 위 처럼 heights에 0을 추가하고 stack에 -1을 넣고 시작하면 코너 케이스 검증을 회피할 수 있다.
My Solution 2 :
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
stack = []
area = i = 0
while i < len(heights):
while stack and heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
if stack:
w = i - stack[-1] - 1
else:
w = i
area = max(area, h*w)
stack.append(i)
i += 1
while stack:
h = heights[stack.pop()]
if stack:
w = i - stack[-1] - 1
else:
w = i
area = max(area, h*w)
return area
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 124. Binary Tree Maximum Path Sum (0) | 2019.04.20 |
---|---|
[LeetCode][Python3] 322. Coin Change (0) | 2019.04.20 |
[LeetCode][Python3] 54. Spiral Matrix (0) | 2019.04.18 |
[LeetCode][Python3] 76. Minimum Window Substring (0) | 2019.04.16 |
[LeetCode][Python3] 79. Word Search (0) | 2019.04.13 |
[LeetCode][Python3] 313. Super Ugly Number (0) | 2019.04.13 |
[LeetCode][Python3] 218. The Skyline Problem (0) | 2019.04.11 |
[LeetCode][Python3] 150. Evaluate Reverse Polish Notation (0) | 2019.04.10 |
최근에 달린 댓글 최근에 달린 댓글