
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find maximum array sum after making all elements same with repeated subtraction in C++
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
#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
- Related Questions & Answers
- Maximum subarray sum in an array created after repeated concatenation in C++
- Maximum subarray sum in an array created after repeated concatenation in C++ Program
- Maximum Subarray Sum after inverting at most two elements in C++
- Finding smallest sum after making transformations in JavaScript
- C++ Program to find array after removal from maximum
- Maximum number of contiguous array elements with same number of set bits in C++
- Maximize the subarray sum after multiplying all elements of any subarray with X in C++
- How to find the sum of all array elements in R?
- Program to check maximum sum of all stacks after popping some elements from them in Python
- Find all triplets with zero sum in C++
- Find smallest subarray that contains all elements in same order in C++
- Maximum array sum that can be obtained after exactly k changes in C++
- Program to find maximum adjacent absolute value sum after single reversal in C++
- Minimum delete operations to make all elements of array same in C++.
- Count array elements that divide the sum of all other elements in C++