Minimum decrement operations to make Array elements equal by only decreasing K each time | javascript implementation of the above approach ; Finding the minimum element ; Loop over all the elements and find the difference ; Solution found and returned ; Driver code
var INT_MAX = Number . MAX_VALUE ; function solve ( arr , n , k ) { var minx = INT_MAX ; var i ; for ( i = 0 ; i < n ; i ++ ) { minx = Math . min ( minx , arr [ i ] ) ; } var decrements = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] - minx ) % k != 0 ) { return - 1 ; } else { decrements += ( ( arr [ i ] - minx ) / k ) ; } } return decrements ; } var n , k ; n = 3 ; k = 3 ; var arr = [ 12 , 9 , 15 ] ; document . write ( solve ( arr , n , k ) ) ;