Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Apr 14, 2024
1 parent 7f1ae86 commit d31df19
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions leetcode/85.MaximalRectangle/sol.go
Original file line number Diff line number Diff line change
@@ -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))
}

0 comments on commit d31df19

Please sign in to comment.