Maximize cost of removing all occurrences of substrings " ab " and " ba " | 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 ; Input String ; Costs
function MaxCollection ( S , P , Q ) { let maxstr = ( P >= Q ? " " : " " ) . split ( " " ) ; let minstr = ( P >= Q ? " " : " " ) . split ( " " ) ; let maxp = Math . max ( P , Q ) ; let minp = Math . min ( P , Q ) ; let cost = 0 ; let stack1 = [ ] ; let s = S . split ( " " ) ; for ( let ch = 0 ; ch < s . length ; ch ++ ) { if ( stack1 . length != 0 && ( stack1 [ stack1 . length - 1 ] == maxstr [ 0 ] && s [ ch ] == maxstr [ 1 ] ) ) { stack1 . pop ( ) ; cost += maxp ; } else { stack1 . push ( s [ ch ] ) ; } } let sb = [ ] ; while ( stack1 . length != 0 ) sb . push ( stack1 . pop ( ) ) ; sb = sb . reverse ( ) ; let remstr = sb . join ( " " ) ; for ( let ch = 0 ; ch < remstr . length ; ch ++ ) { if ( stack1 . length != 0 && ( stack1 [ stack1 . length - 1 ] == minstr [ 0 ] && remstr [ ch ] == minstr [ 1 ] ) ) { stack1 . pop ( ) ; cost += minp ; } else { stack1 . push ( remstr [ ch ] ) ; } } return cost ; } let S = " " ; let P = 6 ; let Q = 4 ; document . write ( MaxCollection ( S , P , Q ) ) ;