42-trapping-rain-water

This commit is contained in:
Kaushik Narayan R 2023-10-27 21:09:24 -07:00
parent d9298b9600
commit ec5227eae8
3 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> 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;
}

View File

@ -0,0 +1,34 @@
#include "soln.hpp"
// Neetcode's two pointer approach
int Solution::trap(vector<int> &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<int> &height, int answer)
{
return trap(height) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int trap(vector<int> &height);
bool test(vector<int> &height, int answer);
};