Answer to Question #303976 in C++ for Manish

Question #303976

Write a function that takes an array of integers as input and prints the second-maximum difference between any two elements from an array.

1
Expert's answer
2022-03-01T01:35:03-0500
#include <bits/stdc++.h>
using namespace std;

int maxDiff(int arr[], int arr_size){	
  int max_diff = arr[1] - arr[0];
  for (int i = 0; i < arr_size; i++)
    for (int j = i+1; j < arr_size; j++)	
      if (arr[j] - arr[i] > max_diff)
        max_diff = arr[j] - arr[i];	
  return max_diff;
}

int main(){
  int arr[] = {1, 2, 90, 10, 110};
  int n = sizeof(arr) / sizeof(arr[0]);
  cout << "Maximum difference is " << maxDiff(arr, n);
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog