Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MaxDifferenceInArray.cpp #1817

Merged
merged 1 commit into from
Oct 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Program's_Contributed_By_Contributors/C++/MaxDifferenceInArray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <iostream>
#include <cmath>
using namespace std;

int main(){
int n;
cout << "Enter the number of elements in the given array: ";
//taking input
cin >> n;
int a[n];
cout << "Enter the elements" << endl;
for (int i = 0; i < n; i++)
cin >> a[i];

//easy way to find the maximum difference between 2
//elements in a given array is to find the difference
//between maximum and minimum elements in the array

int min = a[0], max = a[0];
//applying linear search to find minimum and maximum of the given array
for (int i = 1; i <n; i++){
if (a[i] < min)
min = a[i];
if (a[i] > max)
max = a[i];
}

//printing the difference
cout << "The maximum difference between 2 elements in the given array is " << abs(max - min);
return 0;
}