1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

cpp: add «42. Trapping Rain Water»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-04-13 00:36:43 +02:00
parent 4a2d886d3f
commit e9a5706e93
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,26 @@
#include <algorithm>
#include <vector>
class Solution {
public:
int trap(const std::vector<int> &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;
}
};