Trapping Rain Water | Javascript implementation of the approach ; indices to traverse the array ; To store Left max and right max for two pointers left and right ; To store the total amount of rain water trapped ; We need check for minimum of left and right max for each element ; Add the difference between current value and right max at index r ; Update right max ; Update right pointer ; Add the difference between current value and left max at index l ; Update left max ; Update left pointer ; Driver code
function maxWater ( arr , n ) { let left = 0 ; let right = n - 1 ; let l_max = 0 ; let r_max = 0 ; let result = 0 ; while ( left <= right ) { if ( r_max <= l_max ) { result += Math . max ( 0 , r_max - arr [ right ] ) ; r_max = Math . max ( r_max , arr [ right ] ) ; right -= 1 ; } else { result += Math . max ( 0 , l_max - arr [ left ] ) ; l_max = Math . max ( l_max , arr [ left ] ) ; left += 1 ; } } return result ; } let arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] ; let n = arr . length ; document . write ( maxWater ( arr , n ) ) ;