Browse Source

feat: maximum_rectangle

Zhang Li 1 year ago
parent
commit
7161006a6c
2 changed files with 76 additions and 1 deletions
  1. 74 0
      src/solutions/stack/maximum_rectangle.rs
  2. 2 1
      src/solutions/stack/mod.rs

+ 74 - 0
src/solutions/stack/maximum_rectangle.rs

@@ -0,0 +1,74 @@
+struct Solution;
+
+impl Solution {
+    pub fn maximal_rectangle(matrix: Vec<Vec<char>>) -> i32 {
+        let rows = matrix.len();
+        let cols = matrix[0].len();
+
+        let mut heights = vec![0; cols];
+        let mut max_area = 0;
+
+        for i in 0..rows {
+            for j in 0..cols {
+                if matrix[i][j] == '1' {
+                    heights[j] = heights[j] + 1;
+                } else {
+                    heights[j] = 0;
+                }
+            }
+
+            max_area = max_area.max(Solution::largest_rectangle_area(&heights));
+        }
+
+        max_area
+
+    }
+
+    fn largest_rectangle_area(heights: &Vec<i32>) -> i32 {
+        let mut max_area = 0;
+        let l = heights.len();
+        if l == 0 { return 0; }
+        if l == 1 { return heights[0]; }
+        let mut v = vec![0; l + 2];
+        for i in 0..l {
+            v[i+1] = heights[i];
+        }
+
+        let heights = v;
+        let mut stack = std::collections::VecDeque::new();
+        for i in 0..heights.len() {
+            while !stack.is_empty() && heights[*stack.back().unwrap()] > heights[i] {
+                let idx = stack.pop_back().unwrap();
+                let height = heights[idx];
+                let width = i as i32 -  *stack.back().unwrap() as i32 - 1;
+                max_area = max_area.max(height * width);
+            }
+            stack.push_back(i);
+        }
+
+        max_area
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_maximal_rectangle() {
+        let matrix = vec![vec!['1','0','1','0','0'],vec!['1','0','1','1','1'],vec!['1','1','1','1','1']];
+        let res = Solution::maximal_rectangle(matrix);
+        assert_eq!(res, 6);
+
+    }
+
+    #[test]
+    fn test_maximal_rectangle1() {
+        let matrix = vec![vec!['1']];
+
+        let res = Solution::maximal_rectangle(matrix);
+        assert_eq!(res, 1);
+
+    }
+}

+ 2 - 1
src/solutions/stack/mod.rs

@@ -1,2 +1,3 @@
 mod simplify_path;
-mod largest_rectangle_in_histogram;
+mod largest_rectangle_in_histogram;
+mod maximum_rectangle;