Last Updated: July 28, 2022
·
1.519K
· njucslqq

# Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

``````class Solution {
//O(n) algorithm
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=2)
return 0;
int sum=A[0],mi=0;
for(int i=1;i<n;i++)
{
sum+=A[i];
if(A[i]>A[mi])
mi=i;
}
int left=0,right=0,min=0;
for(int i=1;i<=mi;i++)
if(A[i]>=A[min])
{
left+=A[min]*(i-min);
min=i;
}
min=n-1;
for(int j=n-2;j>=mi;j--)
if(A[j]>=A[min])
{
right+=A[min]*(min-j);
min=j;
}
return left+right+A[mi]-sum;
}
};``````

44.48K
2

16.34K
2

### Prime Numbers with Python

9.955K
1

#### 1 Response

mine is faster

int landscape[] = {0,1,0,2,1,0,1,3,2,1,2,1};
int units = 0 ;
int startBarrrerPos = 0;

int size = sizeof(landscape)/ sizeof(int);

for(int i = 0; i < size-1; i++)
{
if ( landscape[i] >= landscape[startBarrrerPos])
{
startBarrrerPos=i;
continue;
}

``````if ( landscape[i+1] > landscape[i])
{
int increment = (min(landscape[i+1], landscape[startBarrrerPos])) - landscape[i];

if ( landscape[i+1]>= landscape[startBarrrerPos] )
units+= increment * ((i+1 ) -(startBarrrerPos+1));
else
units+=  increment;
}``````

}

over 1 year ago ·

#### Have a fresh tip? Share with Coderwall community!

Best #Algorithm Authors
mbillard
44.48K
antonov
23.82K
bnlucas
13.24K
tripples
7.01K
iam4x
6.069K
Awesome Job