-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode_85.cpp
More file actions
111 lines (90 loc) · 2.28 KB
/
Leetcode_85.cpp
File metadata and controls
111 lines (90 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// 85. Maximal Rectangle
// Time Complexity: O(rows * cols)
// Space Complexity: O(cols)
// Uses stack-based largest rectangle in histogram for each row
#include <vector>
#include <stack>
#include <algorithm>
#include <iostream> // Added for main function
using std::max;
using std::stack;
using std::vector;
// link -https://leetcode.com/problems/maximal-rectangle/description/
/*
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = [["0"]]
Output: 0
Example 3:
Input: matrix = [["1"]]
Output: 1
Constraints:
rows == matrix.length
cols == matrix[i].length
1 <= row, cols <= 200
matrix[i][j] is '0' or '1'.
*/
class Solution
{
public:
int maximalRectangle(vector<vector<char>> &matrix)
{
if (matrix.empty())
return 0;
int maxArea = 0;
int rows = matrix.size(), cols = matrix[0].size();
vector<int> heights(cols, 0);
for (int i = 0; i < rows; ++i)
{
// Build histogram for current row
for (int j = 0; j < cols; ++j)
{
if (matrix[i][j] == '1')
{
heights[j] += 1;
}
else
{
heights[j] = 0;
}
}
maxArea = max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
int largestRectangleArea(vector<int> &heights)
{
stack<int> s;
heights.push_back(0); // Sentinel
int maxArea = 0;
for (int i = 0; i < heights.size(); ++i)
{
while (!s.empty() && heights[i] < heights[s.top()])
{
int h = heights[s.top()];
s.pop();
int w = s.empty() ? i : (i - s.top() - 1);
maxArea = max(maxArea, h * w);
}
s.push(i);
}
heights.pop_back(); // Remove sentinel
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'}};
int result = sol.maximalRectangle(matrix);
std::cout << "Maximal Rectangle Area: " << result << std::endl;
return 0;
}