Maximum number of characters between any two same character in a string | Efficient C ++ program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ) . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; int maximumChars ( string & str ) { int n = str . length ( ) ; int res = -1 ; int firstInd [ MAX_CHAR ] ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) firstInd [ i ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { int first_ind = firstInd [ str [ i ] ] ; if ( first_ind == -1 ) firstInd [ str [ i ] ] = i ; else res = max ( res , abs ( i - first_ind - 1 ) ) ; } return res ; } int main ( ) { string str = " abba " ; cout << maximumChars ( str ) ; return 0 ; }