1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

rs: add «85. Maximal Rectangle»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-04-13 23:56:02 +02:00
parent e9a5706e93
commit 1ab4b55fb1
Signed by: mfocko
GPG key ID: 7C47D46246790496

40
rs/maximal-rectangle.rs Normal file
View file

@ -0,0 +1,40 @@
use std::cmp;
impl Solution {
fn indices(rows: usize, cols: usize) -> impl Iterator<Item = (usize, usize)> {
(0..rows * cols).map(move |i| (i / cols, i % cols))
}
fn get(dp: &[Vec<(usize, usize)>], y: usize, x: usize) -> (usize, usize) {
if y > dp.len() || x > dp[y].len() {
return (0, 0);
}
dp[y][x]
}
pub fn maximal_rectangle(matrix: Vec<Vec<char>>) -> i32 {
let mut found_max = 0;
let mut dp = vec![vec![(0, 0); matrix[0].len()]; matrix.len()];
for (y, x) in Self::indices(matrix.len(), matrix[0].len()) {
if matrix[y][x] != '1' {
continue;
}
let width = 1 + Self::get(&dp, y, x - 1).0;
let height = 1 + Self::get(&dp, y - 1, x).1;
dp[y][x] = (width, height);
found_max = cmp::max(found_max, cmp::max(width, height));
let mut min_width = width;
for yy in ((y - height + 1)..y).rev() {
min_width = cmp::min(min_width, dp[yy][x].0);
found_max = cmp::max(found_max, min_width * (y - yy + 1));
}
}
found_max.try_into().unwrap()
}
}