Subtraction in the Array | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long int NEW_LINE void operations ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; ll i = 0 , sum = 0 ; while ( k -- ) { while ( i < n && arr [ i ] - sum == 0 ) i ++ ; if ( i < n && arr [ i ] - sum > 0 ) { cout << arr [ i ] - sum << " ▁ " ; sum = arr [ i ] ; } else cout << 0 << endl ; } } int main ( ) { int k = 5 ; int arr [ ] = { 3 , 6 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; operations ( arr , n , k ) ; return 0 ; }