mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 08:54:07 +00:00
42-trapping-rain-water
This commit is contained in:
parent
d9298b9600
commit
ec5227eae8
10
42-trapping-rain-water/driver.cpp
Normal file
10
42-trapping-rain-water/driver.cpp
Normal 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;
|
||||||
|
}
|
||||||
34
42-trapping-rain-water/soln.cpp
Normal file
34
42-trapping-rain-water/soln.cpp
Normal 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;
|
||||||
|
}
|
||||||
8
42-trapping-rain-water/soln.hpp
Normal file
8
42-trapping-rain-water/soln.hpp
Normal 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);
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user