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; + } +};