Skip to content

Commit

Permalink
Merge pull request #667 from Vivek-K-M/patch-3
Browse files Browse the repository at this point in the history
Added O(N) time algorithm for max rain water
  • Loading branch information
keshavsingh4522 authored Oct 2, 2021
2 parents ef1f21a + 86fe294 commit 863b459
Showing 1 changed file with 25 additions and 15 deletions.
40 changes: 25 additions & 15 deletions CPP/tappinrainwater.cpp
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
#include<bits/stdc++.h>
using namespace std;

//Efficient implementation with time complexity - O(N).
int maxWater(int arr[], int n)
{

int left = 0;
int right = n-1;
int res = 0;

for (int i = 1; i < n-1; i++) {

int left = arr[i];
for (int j=0; j<i; j++)
left = max(left, arr[j]);

int right = arr[i];
for (int j=i+1; j<n; j++)
right = max(right, arr[j]);

res = res + (min(left, right) - arr[i]);
int maxleft = 0, maxright = 0;
while(left <= right)
{
if(arr[left] <= arr[right])
{
if(arr[left] >= maxleft)
maxleft = arr[left];
else
res += maxleft-arr[left];

left++;
}
else
{
if(arr[right] >= maxright)
maxright = arr[right];
else
res += maxright-arr[right];

right--;
}
}

return res;
}

Expand All @@ -30,4 +40,4 @@ int main()
cout << maxWater(arr, n);

return 0;
}
}

0 comments on commit 863b459

Please sign in to comment.