1. Brute Force — Width Accumulation with Upward Column Scans
Intuition
For each cell, precompute the width of consecutive 1s ending at that cell. For each cell (r, c), scan upwards through rows k from r down to 0, tracking minimum width and updating area minWidth * (r - k + 1).
Algorithm
- Step 1: Compute
width[r][c]= number of consecutive1s ending at (r, c). - Step 2: For each cell (r, c), iterate
kfromrdown to 0. - Step 3: Track
minWidth = min(minWidth, width[k][c]). - Step 4: Update
maxArea = max(maxArea, minWidth * (r - k + 1)).
Width Accumulation with Upward Column Scans Trace
2 of 2 questions left todayMatrix 3x3: r0: ['1','0','1'], r1: ['1','1','1'], r2: ['0','1','1']
Matrix 3x3: r0: [1,0,1], r1: [1,1,1], r2: [0,1,1]. Compute width of consecutive 1s.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: int maximalRectangle(vector<vector<char>>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> width(m, vector<int>(n, 0)); int maxArea = 0; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { if (matrix[r][c] == '1') { width[r][c] = (c == 0 ? 1 : width[r][c - 1] + 1); int minWidth = width[r][c]; for (int k = r; k >= 0 && matrix[k][c] == '1'; k--) { minWidth = min(minWidth, width[k][c]); maxArea = max(maxArea, minWidth * (r - k + 1)); } } } } return maxArea; }}; int main() { Solution sol; vector<vector<char>> matrix = { {'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'} }; cout << "Maximal Rectangle Area (Width Scan): " << sol.maximalRectangle(matrix) << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(M^2 * N)— Precomputes consecutive left widths in O(M * N), then for each cell scans up to M rows upward. - Space complexity:
O(M * N)— Stores an M x N integer table of horizontal widths.
Why Brute Force Doesn't Scale:
For a 200x200 matrix, 2006 = 6.4 * 1013 operations, taking days to finish.
Monotonic stack reduction processes 200x200 in 40,000 operations (< 1ms).