Skip to content

Commit

Permalink
Maximal Rectangle
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 16, 2023
1 parent a5eb7de commit 8c853f7
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ add_task(max-number-of-k-sum-pairs)
add_task(max-pair-sum-in-an-array)
add_task(max-points-on-a-line)
add_task(maximal-network-rank)
add_task(maximal-rectangle)
add_task(maximal-square)
add_task(maximize-score-after-n-operations)
add_task(maximize-the-confusion-of-an-exam)
Expand Down
1 change: 1 addition & 0 deletions solutions/maximal-rectangle/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_maximal_rectangle test.cpp)
38 changes: 38 additions & 0 deletions solutions/maximal-rectangle/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#pragma once

#include <stack>
#include <vector>

class Solution {
public:
static int maximalRectangle(const std::vector<std::vector<char>> &matrix) {
const int n = matrix.size(), m = matrix.back().size();

int max_rectangle = 0;
std::vector<int> heights(m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
heights[j] = matrix[i][j] == '0' ? 0 : heights[j] + 1;
}
max_rectangle = std::max(max_rectangle, largestRectangleArea(heights));
}
return max_rectangle;
}

private:
static int largestRectangleArea(const std::vector<int> &heights) {
const int n = heights.size();
std::stack<int> stack;
int max_area = 0;
for (int i = 0; i <= n; ++i) {
while (!stack.empty() && (i == n || heights[stack.top()] > heights[i])) {
const auto height = heights[stack.top()];
stack.pop();
const auto width = stack.empty() ? i : i - stack.top() - 1;
max_area = std::max(max_area, height * width);
}
stack.push(i);
}
return max_area;
}
};
33 changes: 33 additions & 0 deletions solutions/maximal-rectangle/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::vector<std::vector<char>> matrix;
int expected;
};

std::vector<TestCase> test_cases{
{
.matrix{{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}},
.expected = 6,
},
{
.matrix{{'0'}},
.expected = 0,
},
{
.matrix{{'1'}},
.expected = 1,
},
};

for (const auto &[matrix, expected] : test_cases) {
const auto actual = Solution::maximalRectangle(matrix);
REQUIRE(expected == actual);
}
}

0 comments on commit 8c853f7

Please sign in to comment.