Minimum operation require to make first and last character same | CPP program to minimum operation require to make first and last character same ; Recursive function call ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = INT_MAX ; int minOperation ( string & s , int i , int j , int count ) { if ( ( i >= s . size ( ) && j < 0 ) || ( i == j ) ) return MAX ; if ( s [ i ] == s [ j ] ) return count ; if ( i >= s . size ( ) ) return minOperation ( s , i , j - 1 , count + 1 ) ; else if ( j < 0 ) return minOperation ( s , i + 1 , j , count + 1 ) ; else return min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) ; } int main ( ) { string s = " bacdefghipalop " ; int ans = minOperation ( s , 0 , s . size ( ) - 1 , 0 ) ; if ( ans == MAX ) cout << -1 ; else cout << ans ; return 0 ; }