Maximize cost obtained by removal of substrings " pr " or " rp " from a given String | Function to maintain the case , X >= Y ; To maintain X >= Y ; Replace ' p ' to ' r ' ; Replace ' r ' to ' p ' . ; Function to return the maximum cost ; Stores the length of the String ; To maintain X >= Y . ; Stores the maximum cost ; Stores the count of ' p ' after removal of all " pr " subStrings up to str [ i ] ; Stores the count of ' r ' after removal of all " pr " subStrings up to str [ i ] ; Stack to maintain the order of characters after removal of subStrings ; If subString " pr " is removed ; Increase cost by X ; If any subString " rp " left in the Stack ; If any subString " rp " left in the Stack ; Driver Code
function swapXandY ( str , X , Y ) { let N = str . length ; X = X + Y ; Y = X - Y ; X = X - Y ; for ( let i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' ' ) { str [ i ] = ' ' ; } else if ( str [ i ] == ' ' ) { str [ i ] = ' ' ; } } return true ; } function maxCost ( str , X , Y ) { let N = str . length ; if ( Y > X ) { swapXandY ( str . split ( ' ' ) , X , Y ) ; } let res = 0 ; let countP = 0 ; let countR = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' ' ) { countP ++ ; } else if ( str [ i ] == ' ' ) { if ( countP > 0 ) { countP -- ; res += X ; } else countR ++ ; } else { res += Math . min ( countP , countR ) * Y ; countP = 0 ; countR = 0 ; } } res += Math . min ( countP , countR ) * Y ; return res ; } let str = " " ; let X = 5 , Y = 4 ; document . write ( maxCost ( str , X , Y ) ) ;