From ec5227eae8ae6326f912adc1a8dabd7b358a2778 Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Fri, 27 Oct 2023 21:09:24 -0700 Subject: [PATCH] 42-trapping-rain-water --- 42-trapping-rain-water/driver.cpp | 10 +++++++++ 42-trapping-rain-water/soln.cpp | 34 +++++++++++++++++++++++++++++++ 42-trapping-rain-water/soln.hpp | 8 ++++++++ 3 files changed, 52 insertions(+) create mode 100644 42-trapping-rain-water/driver.cpp create mode 100644 42-trapping-rain-water/soln.cpp create mode 100644 42-trapping-rain-water/soln.hpp diff --git a/42-trapping-rain-water/driver.cpp b/42-trapping-rain-water/driver.cpp new file mode 100644 index 0000000..2ce8aaa --- /dev/null +++ b/42-trapping-rain-water/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + vector heights{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + int answer = 6; + Solution soln; + cout << "Found trapped water amount correctly? " << soln.test(heights, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/42-trapping-rain-water/soln.cpp b/42-trapping-rain-water/soln.cpp new file mode 100644 index 0000000..9c9c928 --- /dev/null +++ b/42-trapping-rain-water/soln.cpp @@ -0,0 +1,34 @@ +#include "soln.hpp" + +// Neetcode's two pointer approach +int Solution::trap(vector &height) +{ + if (height.size() < 3) + return 0; + int water = 0; + int left = 0, right = height.size() - 1; + int left_max = height[left], right_max = height[right]; + bool coming_from_left; + while (left < right) + { + coming_from_left = left_max <= right_max; + if (coming_from_left) + { + left++; + water += max(left_max - height[left], 0); + left_max = max(left_max, height[left]); + } + else + { + right--; + water += max(right_max - height[right], 0); + right_max = max(right_max, height[right]); + } + } + return water; +} + +bool Solution::test(vector &height, int answer) +{ + return trap(height) == answer; +} diff --git a/42-trapping-rain-water/soln.hpp b/42-trapping-rain-water/soln.hpp new file mode 100644 index 0000000..312f9ca --- /dev/null +++ b/42-trapping-rain-water/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + int trap(vector &height); + bool test(vector &height, int answer); +}; \ No newline at end of file