85.Maximal-Rectangle

85. Maximal Rectangle

题目地址

https://leetcode.com/problems/maximal-rectangle/

题目描述

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:
Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

代码

Approach #1 Brute Force

Trivially we can enumerate every possible rectangle. This is done by iterating over all possible combinations of coordinates (x1, y1) and (x2, y2) and letting them define a rectangle with the coordinates being opposite corners. This is too slow to pass all test cases.

Time: O(N^3) Space: O(1)

Better Brote force

Time: O(N^2) Space: O(1)

Approach #2 Dynamic Programming

Complexity Analysis

  • Time complexity : O(N^2 * M)

  • Space complexity : O(NM)

dp[i][j] 在第i行中,0 - j 列的最大宽度

Approach #3 Using Histograms - Stack

  • Time complexity: O(n)

  • Space complexity: O(n)

转化成 Leetcode 84 的单调递增栈

Approach #4 Dynamic Programming - Maximum Height at Each

Complexity Analysis

  • Time complexity : O(NM). In each iteration over N we iterate over M a constant number of times.

  • Space complexity : O(M). M is the length of the additional arrays we keep.

Approach #5 Divde and Conquer

Time: average case: O(n log n) Worst case: O(N^2) Space: O(n)

Better Divde and Conquer

Using a Segment Tree to find the minimum every time which can be done in O(log n) time Time: average case: O(n log n) Space: O(n)

Last updated

Was this helpful?