Minimum sum after subtracting multiples of k from the elements of the array | 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
< ? php function min_sum ( $ n , $ k , $ a ) { sort ( $ a ) ; if ( $ a [ 0 ] < 0 ) return -1 ; if ( $ k == 0 ) { if ( $ a [ 0 ] == $ a [ $ n - 1 ] ) return ( $ n * $ a [ 0 ] ) ; else return -1 ; } else { $ f = 0 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ 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 ) ) ; } } } $ arr = array ( 2 , 3 , 4 , 5 ) ; $ K = 1 ; $ N = count ( $ arr ) ; echo min_sum ( $ N , $ K , $ arr ) ; ? >