Trapping Rain Water | Function to return the maximum water that can be stored ; Let the first element be stored as previous , we shall loop from index 1 ; To store previous wall 's index ; To store the water until a larger wall is found , if there are no larger walls then delete temp value from water ; If the current wall is taller than the previous wall then make current wall as the previous wall and its index as previous wall 's index  for the subsequent loops ; Because larger or same height wall is found ; Since current wall is shorter than the previous , we subtract previous wall ' s ▁ height ▁ from ▁ the ▁ current ▁ wall ' s height and add it to the water ; Store the same value in temp as well If we dont find any larger wall then we will subtract temp from water ; If the last wall was larger than or equal to the previous wall then prev_index would be equal to size of the array ( last element ) If we didn 't find a wall greater than or equal  to the previous wall from the left then  prev_index must be less than the index  of the last element ; Temp would ' ve ▁ stored ▁ the ▁ water ▁ collected ▁ ▁ from ▁ previous ▁ largest ▁ wall ▁ till ▁ the ▁ end ▁ ▁ of ▁ array ▁ if ▁ no ▁ larger ▁ wall ▁ was ▁ found ▁ then ▁ ▁ it ▁ has ▁ excess ▁ water ▁ and ▁ remove ▁ that ▁ ▁ from ▁ ' water ' var ; We start from the end of the array , so previous should be assigned to the last element ; Loop from the end of array up to the ' previous ▁ index ' which would contain the " largest ▁ wall ▁ from ▁ the ▁ left " ; Right end wall will be definitely smaller than the ' previous ▁ index ' wall ; Return the maximum water ; Driver code
def maxWater ( arr , n ) : NEW_LINE INDENT size = n - 1 NEW_LINE prev = arr [ 0 ] NEW_LINE prev_index = 0 NEW_LINE water = 0 NEW_LINE temp = 0 NEW_LINE for i in range ( 1 , size + 1 ) : NEW_LINE INDENT if ( arr [ i ] >= prev ) : NEW_LINE INDENT prev = arr [ i ] NEW_LINE prev_index = i NEW_LINE temp = 0 NEW_LINE DEDENT else : NEW_LINE INDENT water += prev - arr [ i ] NEW_LINE temp += prev - arr [ i ] NEW_LINE DEDENT DEDENT if ( prev_index < size ) : NEW_LINE INDENT water -= temp NEW_LINE prev = arr [ size ] NEW_LINE for i in range ( size , prev_index - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] >= prev ) : NEW_LINE INDENT prev = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT water += prev - arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return water NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxWater ( arr , n ) ) NEW_LINE