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
< ? php function minSwap ( $ arr , $ n , $ k ) { $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) if ( $ arr [ $ i ] <= $ k ) ++ $ count ; $ bad = 0 ; for ( $ i = 0 ; $ i < $ count ; ++ $ i ) if ( $ arr [ $ i ] > $ k ) ++ $ bad ; $ ans = $ bad ; for ( $ i = 0 , $ j = $ count ; $ j < $ n ; ++ $ i , ++ $ j ) { if ( $ arr [ $ i ] > $ k ) -- $ bad ; if ( $ arr [ $ j ] > $ k ) ++ $ bad ; $ ans = min ( $ ans , $ bad ) ; } return $ ans ; } $ arr = array ( 2 , 1 , 5 , 6 , 3 ) ; $ n = sizeof ( $ arr ) ; $ k = 3 ; echo ( minSwap ( $ arr , $ n , $ k ) . " " ) ; $ arr1 = array ( 2 , 7 , 9 , 5 , 8 , 7 , 4 ) ; $ n = sizeof ( $ arr1 ) ; $ k = 5 ; echo ( minSwap ( $ arr1 , $ n , $ k ) ) ; ? >