trap2 worked, but ran out of memory on leetcode. This was my first pass at the problem. I didn't think clearly enough about the memory, which could've been a max(height) x len(height) matrix.
(height []int)
| 36 | // I didn't think clearly enough about the memory, which |
| 37 | // could've been a max(height) x len(height) matrix. |
| 38 | func trap2(height []int) int { |
| 39 | cols := len(height) |
| 40 | rows := 0 |
| 41 | for _, h := range height { |
| 42 | rows = int(math.Max(float64(h), float64(rows))) |
| 43 | } |
| 44 | |
| 45 | repr := make([][]int, rows) |
| 46 | for i := range repr { |
| 47 | repr[i] = make([]int, cols) |
| 48 | } |
| 49 | |
| 50 | fillCol := 0 |
| 51 | fillRow := rows - 1 |
| 52 | for _, h := range height { |
| 53 | hDecr := h |
| 54 | for hDecr > 0 { |
| 55 | repr[fillRow][fillCol] = 1 |
| 56 | fillRow-- |
| 57 | hDecr-- |
| 58 | } |
| 59 | fillCol++ |
| 60 | fillRow = rows - 1 |
| 61 | } |
| 62 | |
| 63 | waterCnt := 0 |
| 64 | for row := 0; row < rows; row++ { |
| 65 | for col := 0; col < cols; col++ { |
| 66 | if repr[row][col] == 1 { |
| 67 | colCur := col + 1 |
| 68 | colCnt := 0 |
| 69 | foundWall := false |
| 70 | for colCur < cols { |
| 71 | if repr[row][colCur] == 1 { |
| 72 | foundWall = true |
| 73 | break |
| 74 | } |
| 75 | colCur++ |
| 76 | colCnt++ |
| 77 | } |
| 78 | |
| 79 | if foundWall { |
| 80 | waterCnt += colCnt |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | return waterCnt |
| 87 | } |