Program to find the maximum difference between the index of any two different numbers | C ++ implementation of the approach ; Function to return the maximum difference ; Iteratively check from back ; Different numbers ; Iteratively check from the beginning ; Different numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumDiff ( int a [ ] , int n ) { int ind1 = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( a [ 0 ] != a [ i ] ) { ind1 = i ; break ; } } int ind2 = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ n - 1 ] != a [ i ] ) { ind2 = ( n - 1 - i ) ; break ; } } return max ( ind1 , ind2 ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMaximumDiff ( a , n ) ; return 0 ; }