
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Difference Between Indexes of Two Different Numbers in C++
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
#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
Advertisements