From 78b7c57b4008263b7b825f08772486cacd257e27 Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Mon, 2 Oct 2023 21:05:36 -0700 Subject: [PATCH] Stack method solved --- .../84_Largest_Rectangle_in_Histogram.py | 44 +++++++------------ NeetCodeRoadmap/Stack/tempCodeRunnerFile.py | 14 ++++-- 2 files changed, 27 insertions(+), 31 deletions(-) diff --git a/NeetCodeRoadmap/Stack/84_Largest_Rectangle_in_Histogram.py b/NeetCodeRoadmap/Stack/84_Largest_Rectangle_in_Histogram.py index 318499d..fb07c56 100644 --- a/NeetCodeRoadmap/Stack/84_Largest_Rectangle_in_Histogram.py +++ b/NeetCodeRoadmap/Stack/84_Largest_Rectangle_in_Histogram.py @@ -4,37 +4,27 @@ class Solution(object): :type heights: List[int] :rtype: int """ - rect = [] - h = len(heights) + heights.append(0) + stack = [-1] + ans = 0 + for i in range(len(heights)): + while heights[i] < heights[stack[-1]]: + h = heights[stack.pop()] + w = i - stack[-1] - 1 + ans = max(ans, h * w) + stack.append(i) + heights.pop() + return ans - if len(heights) <= 2: - if len(heights) == 1: - return heights[0] - else: - if heights[0] == 0 or heights[1] == 0: - return max(heights[0], heights[1]) - low = min(heights[0], heights[1]) - return low*2 - - for x in range(h): - count = 1 - for y in range(x+1, h): - if heights[x] == min(heights): - rect.append(heights[x]*len(heights)) - elif heights[x] > heights[y]: - # print(f'{heights[x]} * {count} = {heights[x]*count}') - rect.append(heights[x]*count) - else: - count += 1 - - if rect: - return max(rect) - else: - return 0 obj = Solution() # print(obj.largestRectangleArea([2,1,5,6,2,3])) # 10 # print(obj.largestRectangleArea([2,4])) # 4 # print(obj.largestRectangleArea([0,9])) # 9 # print(obj.largestRectangleArea([0,0,0])) # 0 # print(obj.largestRectangleArea([2,1,2])) # 3 -print(obj.largestRectangleArea([1,2,2]) # 4 \ No newline at end of file +# print(obj.largestRectangleArea([1,2,2])) # 4 +# print(obj.largestRectangleArea([0,2,0])) # 2 +# print(obj.largestRectangleArea([5,4,1,2])) # 8 +# print(obj.largestRectangleArea([2,0,2])) # 2 +# print(obj.largestRectangleArea([1,2,3,4,5])) # 9 +# print(obj.largestRectangleArea([4,2,0,3,2,5])) # 6 diff --git a/NeetCodeRoadmap/Stack/tempCodeRunnerFile.py b/NeetCodeRoadmap/Stack/tempCodeRunnerFile.py index 5fa34dc..a1745ec 100644 --- a/NeetCodeRoadmap/Stack/tempCodeRunnerFile.py +++ b/NeetCodeRoadmap/Stack/tempCodeRunnerFile.py @@ -1,4 +1,10 @@ -print(obj.largestRectangleArea([2,1,5,6,2,3])) # 10 -print(obj.largestRectangleArea([2,4])) # 4 -print(obj.largestRectangleArea([0,9])) # 9 -print(obj.largestRectangleArea([0,0,0])) # 9 \ No newline at end of file + stack = [-1] + ans = 0 + for i in xrange(len(height)): + while height[i] < height[stack[-1]]: + h = height[stack.pop()] + w = i - stack[-1] - 1 + ans = max(ans, h * w) + stack.append(i) + height.pop() + return ans \ No newline at end of file