Skip to content

Commit

Permalink
Solve: Trapping Rain Water
Browse files Browse the repository at this point in the history
  • Loading branch information
fkdl0048 committed Oct 8, 2024
1 parent 5d21ea3 commit b77ef1f
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions LeetCode/Trapping Rain Water.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
public:
int trap(vector<int>& height) {
if (height.empty()) return 0;

int left = 0, right = height.size() - 1;
int left_max = 0, right_max = 0;
int total_water = 0;

while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= left_max) {
left_max = height[left];
} else {
total_water += left_max - height[left];
}
left++;
} else {
if (height[right] >= right_max) {
right_max = height[right];
} else {
total_water += right_max - height[right];
}
right--;
}
}

return total_water;
}
};

0 comments on commit b77ef1f

Please sign in to comment.