Minimize steps required to make all array elements same by adding 1 , 2 or 5 | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate_steps ( int arr [ ] , int n , int minimum ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int val = arr [ i ] ; if ( arr [ i ] > minimum ) { arr [ i ] = arr [ i ] - minimum ; count += arr [ i ] / 5 ; arr [ i ] = arr [ i ] % 5 ; count += arr [ i ] / 2 ; arr [ i ] = arr [ i ] % 2 ; if ( arr [ i ] ) { count ++ ; } } arr [ i ] = val ; } return count ; } int solve ( int arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; int minimum = arr [ n - 1 ] ; int 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 min ( count1 , min ( count2 , count3 ) ) ; } int main ( ) { int arr [ ] = { 3 , 6 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << solve ( arr , N ) ; }