Minimum swaps required to bring all elements less than or equal to k together | Utility function to find minimum swaps required to club all elements less than or equals to k together ; Find count of elements which are less than equals to k ; Find unwanted elements in current window of size 'count   ; Initialize answer with ' bad ' value of current window ; Decrement count of previous window ; Increment count of current window ; Update ans if count of ' bad ' is less in current window ; Driver code
def minSwap ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] <= k ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT bad = 0 NEW_LINE for i in range ( 0 , count ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT bad = bad + 1 NEW_LINE DEDENT DEDENT ans = bad NEW_LINE j = count NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( j == n ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ i ] > k ) : NEW_LINE INDENT bad = bad - 1 NEW_LINE DEDENT if ( arr [ j ] > k ) : NEW_LINE INDENT bad = bad + 1 NEW_LINE DEDENT ans = min ( ans , bad ) NEW_LINE j = j + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 5 , 6 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( minSwap ( arr , n , k ) ) NEW_LINE arr1 = [ 2 , 7 , 9 , 5 , 8 , 7 , 4 ] NEW_LINE n = len ( arr1 ) NEW_LINE k = 5 NEW_LINE print ( minSwap ( arr1 , n , k ) ) NEW_LINE