cpp: add «42. Trapping Rain Water»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
4a2d886d3f
commit
e9a5706e93
1 changed files with 26 additions and 0 deletions
26
cpp/trapping-rain-water.cpp
Normal file
26
cpp/trapping-rain-water.cpp
Normal 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;
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue