Minimum decrement operations to make Array elements equal by only decreasing K each time | C ++ implementation of the above approach ; Finding the minimum element ; Loop over all the elements and find the difference ; Solution found and returned ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli  long long int NEW_LINE lli solve ( lli arr [ ] , lli n , lli k ) { lli i , minx = INT_MAX ; for ( i = 0 ; i < n ; i ++ ) { minx = min ( minx , arr [ i ] ) ; } lli decrements = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] - minx ) % k != 0 ) { return -1 ; } else { decrements += ( ( arr [ i ] - minx ) / k ) ; } } return decrements ; } int main ( ) { lli n , k ; n = 3 ; k = 3 ; lli arr [ n ] = { 12 , 9 , 15 } ; cout << solve ( arr , n , k ) ; }