Minimize steps required to make all array elements same by adding 1 , 2 or 5 | Function to calculate the minimum number of steps ; count stores number of operations required to make all elements equal to minimum value ; Remark , the array should remain unchanged for further calculations with different minimum ; Storing the current value of arr [ i ] in val ; Finds how much extra amount is to be removed ; Subtract the maximum number of 5 and stores remaining ; Subtract the maximum number of 2 and stores remaining ; Restores the actual value of arr [ i ] ; Return the count ; Function to find the minimum number of steps to make array elements same ; Sort the array in descending order ; Stores the minimum array element ; Stores the operations required to make array elements equal to minimum ; Stores the operations required to make array elements equal to minimum - 1 ; Stores the operations required to make array elements equal to minimum - 2 ; Return minimum of the three counts ; Driver Code
function calculate_steps ( arr , n , minimum ) { var count = 0 ; for ( var i = 0 ; i < n ; i ++ ) { var val = arr [ i ] ; if ( arr [ i ] > minimum ) { arr [ i ] = arr [ i ] - minimum ; count += parseInt ( arr [ i ] / 5 ) ; arr [ i ] = arr [ i ] % 5 ; count += parseInt ( arr [ i ] / 2 ) ; arr [ i ] = arr [ i ] % 2 ; if ( arr [ i ] ) { count ++ ; } } arr [ i ] = val ; } return count ; } function solve ( arr , n ) { arr . sort ( ( a , b ) => b - a ) ; var minimum = arr [ n - 1 ] ; var count1 = 0 , count2 = 0 , count3 = 0 ; count1 = calculate_steps ( arr , n , minimum ) ; count2 = calculate_steps ( arr , n , minimum - 1 ) ; count3 = calculate_steps ( arr , n , minimum - 2 ) ; return Math . min ( count1 , Math . min ( count2 , count3 ) ) ; } var arr = [ 3 , 6 , 6 ] ; var N = arr . length ; document . write ( solve ( arr , N ) ) ;