From e9a5706e933573e5db96258137d728f0ee3cdfa0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 13 Apr 2024 00:36:43 +0200 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB42.=20Trapping=20Rain=20Wate?= =?UTF-8?q?r=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/trapping-rain-water.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 cpp/trapping-rain-water.cpp diff --git a/cpp/trapping-rain-water.cpp b/cpp/trapping-rain-water.cpp new file mode 100644 index 0000000..fd5c386 --- /dev/null +++ b/cpp/trapping-rain-water.cpp @@ -0,0 +1,26 @@ +#include +#include + +class Solution { + public: + int trap(const std::vector &height) { + int caught = 0; + + auto i = 0u; + auto j = height.size() - 1; + + int max_l = height[i], max_r = height[j]; + while (i < j) { + max_l = std::max(max_l, height[i]); + max_r = std::max(max_r, height[j]); + + if (max_l < max_r) { + caught += max_l - height[i++]; + } else { + caught += max_r - height[j--]; + } + } + + return caught; + } +};