Minimum sum after subtracting multiples of k from the elements of the array | C ++ program of the above approach ; function to calculate minimum sum after transformation ; no element can be reduced further ; if all the elements of the array are identical ; check if a [ i ] can be reduced to a [ 0 ] ; one of the elements cannot be reduced to be equal to the other elements ; if k = 1 then all elements can be reduced to 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_sum ( int n , int k , int a [ ] ) { sort ( a , a + n ) ; if ( a [ 0 ] < 0 ) return -1 ; if ( k == 0 ) { if ( a [ 0 ] == a [ n - 1 ] ) return ( n * a [ 0 ] ) ; else return -1 ; } else { int f = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int p = a [ i ] - a [ 0 ] ; if ( p % k == 0 ) continue ; else { f = 1 ; break ; } } if ( f ) return -1 ; else { if ( k == 1 ) return n ; else return ( n * ( a [ 0 ] % k ) ) ; } } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 } ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << min_sum ( N , K , arr ) ; return 0 ; }