Find maximum array sum after making all elements same with repeated subtraction in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of n elements. Find the maximum possible sum of all elements such that all the elements are same. Only operation that is allowed is choosing any two elements and replacing the larger of them by the absolute difference of the two. Suppose elements are like [9, 12, 3, 6]. Then the output will be 12. So at first replace A[1] with A[1] – A[3] = 12 – 6 = 6. So now elements are [9, 6, 3, 6], then replace A[3] with A[3] – A[2] = 6 – 3 = 3. So the elements are [9, 6, 3, 3]. Then replace A[0] with A[0] – A[1] = 9 – 6 = 3. So the elements are [3, 6, 3, 3]. And finally replace A[1] with A[1] – A[3] = 6 – 3 = 3. So the elements are [3, 3, 3, 3]. So all are same. And sum is 12

If we analyze the operation, it will be A[i] = A[i] – A[j], where A[i] > A[j]. So we will take two numbers, then replace the larger value by the absolute difference of them. Then repeat these steps until all are same.

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int findSameElement(int arr[], int n) {
   int gcd_val = arr[0];
   for (int i = 1; i < n; i++)
   gcd_val = __gcd(arr[i], gcd_val);
   return gcd_val;
}
int getMaxSum(int arr[], int n) {
   int value = findSameElement(arr, n);
   return (value * n);
}
int main() {
   int arr[] = {3, 9, 6, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "The maximum sum is: " << getMaxSum(arr, n);
}

Output

The maximum sum is: 12
raja
Published on 18-Dec-2019 11:01:20
Advertisements