diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /trapping_rain_water.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'trapping_rain_water.cpp')
-rw-r--r-- | trapping_rain_water.cpp | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/trapping_rain_water.cpp b/trapping_rain_water.cpp new file mode 100644 index 0000000..d2ced43 --- /dev/null +++ b/trapping_rain_water.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + int trap(vector<int> &height) { + if (height.size() <= 2) + return 0; + int n = height.size(), maxLeft = height[0], maxRight = height[n - 1]; + int left = 1, right = n - 2, ans = 0; + while (left <= right) { + if (maxLeft < maxRight) { + if (height[left] > maxLeft) + maxLeft = height[left]; + else + ans += maxLeft - height[left]; + left += 1; + } else { + if (height[right] > maxRight) + maxRight = height[right]; + else + ans += maxRight - height[right]; + right -= 1; + } + } + return ans; + } +}; + +int main() { + Solution obj; + vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + cout << obj.trap(height); +} |