From d31df1982fac9ceccef3311d15735e4218a005b5 Mon Sep 17 00:00:00 2001 From: ductnn Date: Sun, 14 Apr 2024 18:01:38 +0700 Subject: [PATCH] add sol --- leetcode/85.MaximalRectangle/sol.go | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 leetcode/85.MaximalRectangle/sol.go diff --git a/leetcode/85.MaximalRectangle/sol.go b/leetcode/85.MaximalRectangle/sol.go new file mode 100644 index 0000000..bdc79a2 --- /dev/null +++ b/leetcode/85.MaximalRectangle/sol.go @@ -0,0 +1,65 @@ +// https://leetcode.com/problems/maximal-rectangle/ + +package main + +import "fmt" + +func maximalRectangle(matrix [][]byte) int { + n := len(matrix[0]) + heights := make([]int, n) + ans := 0 + for _, row := range matrix { + for j, v := range row { + if v == '1' { + heights[j]++ + } else { + heights[j] = 0 + } + } + ans = max(ans, largestRectangleArea(heights)) + } + return ans +} + +func largestRectangleArea(heights []int) int { + res, n := 0, len(heights) + var stk []int + left, right := make([]int, n), make([]int, n) + for i := range right { + right[i] = n + } + for i, h := range heights { + for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { + right[stk[len(stk)-1]] = i + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } else { + left[i] = -1 + } + stk = append(stk, i) + } + for i, h := range heights { + res = max(res, h*(right[i]-left[i]-1)) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func main() { + matrix := [][]byte{ + {'1', '0', '1', '0', '0'}, + {'1', '0', '1', '1', '1'}, + {'1', '1', '1', '1', '1'}, + {'1', '0', '0', '1', '0'}, + } + + fmt.Println(maximalRectangle(matrix)) +}