Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
너비가 1인 고도 지도를 나타내는 음이 아닌 정수 n개가 주어졌을 때, 비가 내린 후에 얼마나 많은 물을 가둘 수 있는지 계산하세요.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
- n == height.length
- 1 <= n <= 2 * 10^4
- 0 <= height[i] <= 10^5
코드
class Solution {
fun trap(height: IntArray): Int {
var l = 0
var r = height.lastIndex
var leftMax = height[l]
var rightMax = height[r]
var answer = 0
while (l < r) {
if (leftMax < rightMax) {
l++
leftMax = maxOf(leftMax, height[l])
answer += leftMax - height[l]
} else {
r--
rightMax = maxOf(rightMax, height[r])
answer += rightMax - height[r]
}
}
return answer
}
}
'LeetCode > Two Pointers' 카테고리의 다른 글
[LeetCod][Kotlin] 948. Bag of Tokens (0) | 2024.11.14 |
---|---|
[LeetCode][Kotlin] 1578. Minimum Time to Make Rope Colorful (0) | 2024.10.19 |
[LeetCode][Kotlin] 779. K-th Symbol in Grammar (0) | 2024.10.19 |