Minimize adding odd and subtracting even numbers to make all array elements equal to K | Function to find the minimum operations required to make array elements equal to K ; Stores minimum count of operations ; Traverse the given array ; If K is greater than arr [ i ] ; If ( K - arr [ i ] ) is even ; Update cntOpe ; Update cntOpe ; If K is less than arr [ i ] ; If ( arr [ i ] - K ) is even ; Update cntOpe ; Update cntOpe ; Driver Code
function MinOperation ( arr , N , K ) { let cntOpe = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( K > arr [ i ] ) { if ( ( K - arr [ i ] ) % 2 == 0 ) { cntOpe += 2 ; } else { cntOpe += 1 ; } } else if ( K < arr [ i ] ) { if ( ( K - arr [ i ] ) % 2 == 0 ) { cntOpe += 1 ; } else { cntOpe += 2 ; } } } return cntOpe ; } let arr = [ 8 , 7 , 2 , 1 , 3 ] ; let K = 5 ; let N = arr . length ; document . write ( MinOperation ( arr , N , K ) ) ;