-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrappingRainWater.kt
55 lines (49 loc) · 1.66 KB
/
TrappingRainWater.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/trapping-rain-water/)
*/
class TrappingRainWater {
fun trap(height: IntArray): Int {
val waterHeight = waterHeight(height)
return waterVolume(height, waterHeight)
}
private fun waterVolume(wallHeight: IntArray, waterHeight: IntArray): Int {
var result = 0
for (i in wallHeight.indices) {
result += waterHeight[i] - wallHeight[i]
}
return result
}
private fun waterHeight(wallHeight: IntArray): IntArray {
val leftWaterHeight = leftToRightWaterHeight(wallHeight)
val rightWaterHeight = rightToLeftWaterHeight(wallHeight)
val result = IntArray(wallHeight.size)
for (i in result.indices) {
result[i] = minOf(
leftWaterHeight[i],
rightWaterHeight[i]
)
}
return result
}
// The height of the water if there is a high wall on the right side
private fun leftToRightWaterHeight(height: IntArray): IntArray {
var maxHeight = 0
val result = IntArray(height.size)
for (i in height.indices) {
maxHeight = maxOf(height[i], maxHeight)
result[i] = maxHeight
}
return result
}
// The height of the water if there is a high wall on the left side
private fun rightToLeftWaterHeight(height: IntArray): IntArray {
var maxHeight = 0
val result = IntArray(height.size)
for (i in height.size - 1 downTo 0) {
maxHeight = maxOf(height[i], maxHeight)
result[i] = maxHeight
}
return result
}
}