| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MaximalRectangle; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximalRectangleStack : IMaximalRectangle |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * m) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="matrix"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MaximalRectangle(char[][] matrix) |
| 3 | 24 | | { |
| 3 | 25 | | var maxArea = 0; |
| 3 | 26 | | var height = new int[matrix[0].Length + 1]; |
| | 27 | |
|
| 21 | 28 | | foreach (var item in matrix) |
| 6 | 29 | | { |
| 6 | 30 | | var stack = new Stack<int>(); |
| | 31 | |
|
| 68 | 32 | | for (var col = 0; col <= matrix[0].Length; col++) |
| 28 | 33 | | { |
| 28 | 34 | | if (col < matrix[0].Length) |
| 22 | 35 | | { |
| 22 | 36 | | if (item[col] == '1') |
| 14 | 37 | | { |
| 14 | 38 | | height[col] += 1; |
| 14 | 39 | | } |
| | 40 | | else |
| 8 | 41 | | { |
| 8 | 42 | | height[col] = 0; |
| 8 | 43 | | } |
| 22 | 44 | | } |
| | 45 | |
|
| 42 | 46 | | while (stack.Count > 0 && height[col] < height[stack.Peek()]) |
| 14 | 47 | | { |
| 14 | 48 | | var h = height[stack.Pop()]; |
| 14 | 49 | | var w = stack.Count == 0 ? col : col - stack.Peek() - 1; |
| 14 | 50 | | maxArea = Math.Max(maxArea, h * w); |
| 14 | 51 | | } |
| | 52 | |
|
| 28 | 53 | | stack.Push(col); |
| 28 | 54 | | } |
| 6 | 55 | | } |
| | 56 | |
|
| 3 | 57 | | return maxArea; |
| 3 | 58 | | } |
| | 59 | | } |