Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class : deflargestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ heights.append(0) stack = [] i = 0 result = 0 while i<len(heights): ifnot stack or heights[stack[-1]]<heights[i]: stack.append(i) i+=1 else: num = stack.pop(-1) result = max(result,heights[num]*(i-stack[-1]-1if stack else i)) return result
Description
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area. Example
At first, I was seeking for Dynamic Programing solutions. But when related this problem to the former Largest Rectangle in Histogram problem, There is a clean solution.
You just need to run a for loop to extend the aforementioned one-dimensional Histigram to a 2-dimensional problem.
class : defmaximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if len(matrix)==0: return0 row = len(matrix) column = len(matrix[0]) temp = [0for i in range(column)] i = 0 result = 0 while i<row: for j in range(column): temp[j] = (0if matrix[i][j]=='0'else temp[j]+1) result = max(result, self.largestRectangleArea(temp)) i+=1 return result deflargestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ heights.append(0) stack = [] i = 0 result = 0 while i<len(heights): ifnot stack or heights[stack[-1]]<heights[i]: stack.append(i) i+=1 else: num = stack.pop(-1) result = max(result,heights[num]*(i-stack[-1]-1if stack else i)) return result
近期评论