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
function segments ( n , p , m ) { var c = new Map ( ) ; c . set ( 0 , 1 ) ; var hs = false ; var sum = 0 ; var ans = 0 ; var r ; for ( r = 0 ; r < n ; r ++ ) { if ( p [ r ] < m ) sum -- ; else if ( p [ r ] > m ) sum ++ ; if ( p [ r ] == m ) hs = true ; if ( hs ) { if ( c . has ( sum ) && c . has ( sum - 1 ) ) ans += c . get ( sum ) + c . get ( sum - 1 ) ; else if ( c . has ( sum ) ) ans += c . get ( sum ) ; else if ( c . has ( sum - 1 ) ) ans += c . get ( sum - 1 ) ; } else { if ( c . has ( sum ) ) c . set ( sum , c . get ( sum ) + 1 ) ; else c . set ( sum , 1 ) ; } } return ans ; } var a = [ 2 , 4 , 5 , 3 , 1 ] ; var n = a . length ; var m = 4 ; document . write ( segments ( n , a , m ) ) ;