Find the number of sub arrays in the permutation of first N natural numbers such that their median is M | C # implementation of the approach ; 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
using System ; using System . Collections . Generic ; class GFG { public static int segments ( int n , int [ ] p , int m ) { Dictionary < int , int > c = new Dictionary < int , int > ( ) ; c . Add ( 0 , 1 ) ; bool has = false ; int sum = 0 ; int ans = 0 ; for ( int 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 . ContainsKey ( sum ) ? 0 : c [ sum ] ) + ( ! c . ContainsKey ( sum - 1 ) ? 0 : c [ sum - 1 ] ) ; else c . Add ( sum , ! c . ContainsKey ( sum ) ? 1 : c [ sum ] + 1 ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] a = { 2 , 4 , 5 , 3 , 1 } ; int n = a . Length ; int m = 4 ; Console . WriteLine ( segments ( n , a , m ) ) ; } }