- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum difference elements that can added to a set in C++
According to the problem we are given a set arr[n] where n is the number of integer elements in the set, the task is to find the maximum difference elements which are to be added to obtain the elements in the set. In other words, the difference should be in form of |a-b| where 'a' and 'b' both are in the set and their difference should not be the least. So, we will count the maximum number of differences which are distinct and largest from a set. Let's understand the problem and its solution with help of an example.
Input − set = {1, 5}
Output − Maximum difference elements that can added to a set is: 1
Explanation − There is only 1 difference in the set i.e. |1-5| = 4
Input − set = {2, 7, 1, 9}
Output − Maximum difference
elements that can added to a set is: 5
Explanation − The differences in the set are as follows −
|2-7| = 5 |7-1| = 6 |1-9| = 8 |2-9| = 7 |7-9| = 2
Approach used in the below program as follows
Take an integer array arr[n] to store the values of the set.
In function maximum() follow steps 3 to 6.
Declare an element ele, temp, val and set their values equal to arr[0]
Loop i from 1 till the size of the array increase it by 1 step.
Find the gcd of all the elements in the array.
Set temp as maximum value between temp or arr[i].
Set total as temp/val and max as the difference of total and size.
Return and print max.
Example
#include <bits/stdc++.h> using namespace std; //function to find maximum difference element int maximum(int arr[], int size){ int ele = arr[0]; int val = ele; int temp = ele; for (int i = 1; i < size; i++){ val = __gcd(val, arr[i]); temp = max(temp, arr[i]); } int total = temp / val; int max = total - size; return max; } int main(){ int arr[] = { 2, 7, 1, 9}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Maximum difference elements that can added to a set is: "<<maximum(arr, size); return 0; }
Output
If we run the above code we will get the following output −
Maximum difference elements that can added to a set is: 5