Maximize cost of removing all occurrences of substrings " ab " and " ba " | C # program for the above approach : ; Function to find the maximum cost of removing substrings " ab " and " ba " from S ; MaxStr is the substring char array with larger cost ; MinStr is the substring char array with smaller cost ; ; Denotes larger point ; Denotes smaller point ; Stores cost scored ; Stack to keep track of characters ; Traverse the string ; If the substring is maxstr ; Pop from the stack ; Add maxp to cost ; Push the character to the stack ; Remaining string after removing maxstr ; Find remaining string ; Reversing the string retrieved from the stack ; Removing all occurences of minstr ; If the substring is minstr ; Pop from the stack ; Add minp to the cost ; Otherwise ; Return the maximum cost ; Driver Code ; Input String ; Costs
using System ; using System . Collections ; class GFG { static int MaxCollection ( string S , int P , int Q ) { char [ ] maxstr = ( P >= Q ? " ab " : " ba " ) . ToCharArray ( ) ; char [ ] minstr = ( P >= Q ? " ba " : " ab " ) . ToCharArray ( ) ; int maxp = Math . Max ( P , Q ) ; int minp = Math . Min ( P , Q ) ; int cost = 0 ; Stack stack1 = new Stack ( ) ; char [ ] s = S . ToCharArray ( ) ; foreach ( char ch in s ) { if ( stack1 . Count > 0 && ( ( char ) stack1 . Peek ( ) == maxstr [ 0 ] && ch == maxstr [ 1 ] ) ) { stack1 . Pop ( ) ; cost += maxp ; } else { stack1 . Push ( ch ) ; } } string sb = " " ; while ( stack1 . Count > 0 ) { sb = sb + stack1 . Peek ( ) ; stack1 . Pop ( ) ; } char [ ] chars = sb . ToCharArray ( ) ; Array . Reverse ( chars ) ; string remstr = new string ( chars ) ; foreach ( char ch in remstr . ToCharArray ( ) ) { if ( stack1 . Count > 0 && ( ( char ) stack1 . Peek ( ) == minstr [ 0 ] && ch == minstr [ 1 ] ) ) { stack1 . Pop ( ) ; cost += minp ; } else { stack1 . Push ( ch ) ; } } return cost ; } static void Main ( ) { string S = " cbbaabbaab " ; int P = 6 ; int Q = 4 ; Console . Write ( MaxCollection ( S , P , Q ) ) ; } }