Subtraction in the Array | Function to perform the given operation on arr [ ] ; Skip elements which are 0 ; Pick smallest non - zero element ; If all the elements of arr [ ] are 0 ; Driver code
function operations ( arr , n , k ) { arr . sort ( ) ; let i = 0 , sum = 0 ; while ( k -- > 0 ) { while ( i < n && arr [ i ] - sum == 0 ) i ++ ; if ( i < n && arr [ i ] - sum > 0 ) { document . write ( arr [ i ] - sum + " " ) ; sum = arr [ i ] ; } else document . write ( " " ) ; } } let k = 5 ; let arr = [ 3 , 6 , 4 , 2 ] ; let n = arr . length ; operations ( arr , n , k ) ;