1. All Subgrid Inspection (Brute Force)
Intuition
Enumerate every possible top-left (r1, c1) and bottom-right (r2, c2) corner, verifying that all cells contain 1.
Algorithm
- 1. Loop r1 from 0 to R-1 and c1 from 0 to C-1.
- 2. Loop r2 from r1 to R-1 and c2 from c1 to C-1.
- 3. Check if all cells in [r1..r2][c1..c2] are
1. - 4. If valid, update maxArea.
- 5. Return maxArea.
Brute Force All Sub-Rectangles All-Ones Check
2 of 2 questions left todayPhase 1 — Step 1: Step 1: Fix top-left corner (0, 0) and bottom-right corner (0, 0)
Phase 1 — Step 1: Step 1: Fix top-left corner (0, 0) and bottom-right corner (0, 0). The cell contains 1. maxArea = 1.
#include <iostream>#include <vector>#include <algorithm>using namespace std; // Brute Force Approach: All Subgrid Inspectionint maximalRectangle(const vector<vector<char>>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int R = matrix.size(), C = matrix[0].size(); int maxArea = 0; for (int r1 = 0; r1 < R; r1++) { for (int c1 = 0; c1 < C; c1++) { for (int r2 = r1; r2 < R; r2++) { for (int c2 = c1; c2 < C; c2++) { bool allOnes = true; for (int r = r1; r <= r2 && allOnes; r++) { for (int c = c1; c <= c2; c++) { if (matrix[r][c] != '1') { allOnes = false; break; } } } if (allOnes) { maxArea = max(maxArea, (r2 - r1 + 1) * (c2 - c1 + 1)); } } } } } return maxArea;} int main() { vector<vector<char>> matrix = { {'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'} }; int result = maximalRectangle(matrix); cout << "Output: " << result << endl; return 0;}Time & Space Complexity
- Time complexity:
O(R^3 * C^3)— There are O(R2 * C2) rectangles; validating each takes O(R * C) time. - Space complexity:
O(1)— Only constant extra memory used.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.