Maximal Rectangle
LeetCode 85 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Row-by-row histograms + largest-rectangle-in-histogram.
ನಾನು Maximal Rectangle (LeetCode 85) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Monotonic Stack – Contribution / Area ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Treat each row as the floor of a histogram: the height of a column is how many consecutive '1's sit on top of that row. The largest rectangle in the matrix is the largest rectangle in one of these histograms, which a monotonic stack finds in linear time.
Approach
- 1
Keep heights[j] for the current row: +1 on a '1', reset to 0 on a '0'.
- 2
Run the histogram routine on every row's heights.
- 3
Histogram: keep a stack of increasing heights; when a lower bar arrives, pop and compute the area each popped bar could span.
- 4
Track the maximum area across all rows.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Histogram per row + monotonic stackPythonO(m·n) time · O(n) space
class Solution:
def largest_recangle_histogram(self,heights):
n = len(heights)
stack = [-1]
max_area = 0
for i in range(n):
#got a smaller height pop
while stack[-1]!=-1 and heights[i]<=heights[stack[-1]]:
cur_height = heights[stack.pop()]
cur_width = i - stack[-1]-1
max_area=max(max_area,cur_height*cur_width)
stack.append(i) #regular append
#full width
while stack[-1]!=-1:
cur_height = heights[stack.pop()]
cur_width = n - stack[-1]-1
max_area=max(max_area,cur_height*cur_width)
return max_area
def maximalRectangle(self, matrix: List[List[str]]) -> int:
n = len(matrix[0])
m = len(matrix)
heights = [0]*n
largest_rect = 0
for i in range(m):
for j in range(n):
if int(matrix[i][j])==1:
heights[j]=1+ heights[j]
else:
heights[j]=0
largest_rect=max(largest_rect,self.largest_recangle_histogram(heights))
return largest_rectMaximal Rectangle — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Maximal Rectangle ಹಿಂದಿನ intuition ಏನು?
Treat each row as the floor of a histogram: the height of a column is how many consecutive '1's sit on top of that row. The largest rectangle in the matrix is the largest rectangle in one of these histograms, which a monotonic stack finds in linear time.
Maximal Rectangle (LeetCode 85) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Keep heights[j] for the current row: +1 on a '1', reset to 0 on a '0'. 2. Run the histogram routine on every row's heights. 3. Histogram: keep a stack of increasing heights; when a lower bar arrives, pop and compute the area each popped bar could span. 4. Track the maximum area across all rows.
Maximal Rectangle ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m · n). Space: O(n). (Accepted approach: Histogram per row + monotonic stack.)
Maximal Rectangle ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
The −1 sentinel on the stack makes the width formula work at the left edge. Flush the remaining stack after the loop with width up to n.