Find the number of sub arrays in the permutation of first N natural numbers such that their median is M | Function to return the count of sub - arrays in the given permutation of first n natural numbers such that their median is m ; If element is less than m ; If element greater than m ; If m is found ; Count the answer ; Increment sum ; Driver code
< ? php function segments ( $ n , $ p , $ m ) { $ c = array ( ) ; $ c [ 0 ] = 1 ; $ has = false ; $ sum = 0 ; $ ans = 0 ; for ( $ r = 0 ; $ r < $ n ; $ r ++ ) { if ( $ p [ $ r ] < $ m ) $ sum -- ; else if ( $ p [ $ r ] > $ m ) $ sum ++ ; if ( $ p [ $ r ] == $ m ) $ has = true ; if ( $ has ) $ ans += $ c [ $ sum ] + $ c [ $ sum - 1 ] ; else $ c [ $ sum ] ++ ; } return $ ans ; } $ a = array ( 2 , 4 , 5 , 3 , 1 ) ; $ n = count ( $ a ) ; $ m = 4 ; echo segments ( $ n , $ a , $ m ) ; ? >