Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal | C # program to implement the above approach ; Function ot find the length of the smallest subarray ; Stores ( prefix Sum , index ) as ( key , value ) mappings ; Iterate till N ; Update the prefixSum ; Update the length ; Put the latest index to find the minimum length ; Update the length ; Return the answer ; Function to find the length of the largest subarray ; Stores the sum of all array elements after modification ; Change greater than k to 1 ; Change smaller than k to - 1 ; Change equal to k to 0 ; Update total_sum ; No deletion required , return 0 ; Delete smallest subarray that has sum = total_sum ; Driver Code ; Function call
using System ; using System . Collections . Generic ; class GFG { static int smallSubarray ( int [ ] arr , int n , int total_sum ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; int length = int . MaxValue ; int prefixSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { prefixSum += arr [ i ] ; if ( prefixSum == total_sum ) { length = Math . Min ( length , i + 1 ) ; } if ( m . ContainsKey ( prefixSum ) ) m [ prefixSum ] = i ; else m . Add ( prefixSum , i ) ; if ( m . ContainsKey ( prefixSum - total_sum ) ) { length = Math . Min ( length , i - m [ prefixSum - total_sum ] ) ; } } return length ; } static int smallestSubarrayremoved ( int [ ] arr , int n , int k ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > k ) { arr [ i ] = 1 ; } else if ( arr [ i ] < k ) { arr [ i ] = - 1 ; } else { arr [ i ] = 0 ; } total_sum += arr [ i ] ; } if ( total_sum == 0 ) { return 0 ; } else { return smallSubarray ( arr , n , total_sum ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 12 , 16 , 12 , 13 , 10 } ; int K = 13 ; int n = arr . Length ; Console . WriteLine ( smallestSubarrayremoved ( arr , n , K ) ) ; } }