Maximum water that can be stored between two buildings | Return the maximum water that can be stored ; To store the maximum water so far ; Both the pointers are pointing at the first and the last buildings respectively ; While the water can be stored between the currently chosen buildings ; Update maximum water so far and increment i ; Update maximum water so far and decrement j ; Any of the pointers can be updated ( or both ) ; Driver code
function maxWater ( height , n ) { var maximum = 0 ; var i = 0 , j = n - 1 ; while ( i < j ) { if ( height [ i ] < height [ j ] ) { maximum = Math . max ( maximum , ( j - i - 1 ) * height [ i ] ) ; i ++ ; } else if ( height [ j ] < height [ i ] ) { maximum = Math . max ( maximum , ( j - i - 1 ) * height [ j ] ) ; j -- ; } else { maximum = Math . max ( maximum , ( j - i - 1 ) * height [ i ] ) ; i ++ ; j -- ; } } return maximum ; } var height = [ 2 , 1 , 3 , 4 , 6 , 5 ] ; var n = height . length ; document . write ( maxWater ( height , n ) )