diff --git a/swift/42-Trapping-Rain-Water.swift b/swift/42-Trapping-Rain-Water.swift new file mode 100644 index 000000000..8fd569e30 --- /dev/null +++ b/swift/42-Trapping-Rain-Water.swift @@ -0,0 +1,30 @@ +class Solution { + func trap(_ height: [Int]) -> Int { + if height == nil { + return 0 + } + + var res = 0 + var l = 0 + var r = height.count - 1 + + var leftMax = height[l] + var rightMax = height[r] + + while l < r { + if leftMax < rightMax { + l += 1 + leftMax = max(leftMax, height[l]) + res += leftMax - height[l] + } else { + r -= 1 + rightMax = max(rightMax, height[r]) + res += rightMax - height[r] + } + } + + return res + + } + +}
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: