Maximize the given number by replacing a segment of digits with the alternate digits given | C ++ implementation of the approach ; Function to return the maximized number ; Iterate till the end of the string ; Check if it is greater or not ; Replace with the alternate till smaller ; Return original s in case no change took place ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string get_maximum ( string s , int a [ ] ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] - '0' < a [ s [ i ] - '0' ] ) { int j = i ; while ( j < n && ( s [ j ] - '0' <= a [ s [ j ] - '0' ] ) ) { s [ j ] = '0' + a [ s [ j ] - '0' ] ; j ++ ; } return s ; } } return s ; } int main ( ) { string s = "1337" ; int a [ ] = { 0 , 1 , 2 , 5 , 4 , 6 , 6 , 3 , 1 , 9 } ; cout << get_maximum ( s , a ) ; return 0 ; }