Program to find the maximum difference between the index of any two different numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] consisting of n integers. Our task is to create a program to find the maximum difference between the index of any two different numbers in C++.

Code Description − Here, we need to find the maximum difference between the index of integer values of the array, given that the two integers are different.

Let’s take an example to understand the problem,

Input

arr[] = {4, 1, 3, 2, 1, 2, 4}

Output

5

Explanation

The difference between index 0, element 4, and index 5, element 2.

Solution Approach

We will try to find the maximum possible difference between the index of unique elements from the array.

Program to show the implementation of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int maximum(int a, int b){
   if(a > b)
      return a;
      return b;
}
int CalcMaxIndDiff(int a[], int n) {
   int indDiff1 = 0, indDiff2 = 0;
   int i = 0;
   while(i < (n - 1)){
      if(a[0] != a[i]){
         indDiff2 = i;
         break;
      }
      i++;
   }
   i = (n - 1) ;
   while(i > 0){
      if(a[0] != a[i]){
         indDiff1 = i;
         break;
      }
      i--;
   }
   return maximum(indDiff1, indDiff2);
}
int main() {
   int arr[] = { 4, 1, 3, 2, 1, 2, 4 };
   int n = 7;
   cout<<"The maximum difference between the index of any two different numbers is "<<CalcMaxIndDiff(arr, n);
   return 0;
}

Output

The maximum difference between the index of any two different numbers is 5
raja
Published on 08-Jun-2020 14:13:12
Advertisements