Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times | Function to check if a valid parenthesis can be obtained by moving characters to either end at most K number of times ; Base Case 1 ; Count of ' ( ' and ' ) ' ; Base Case 2 ; Store the count of moves required to make a valid parenthesis ; Traverse the string ; Increment cnt if opening bracket has occurred ; Otherwise , decrement cnt by 1 ; Decrement cnt by 1 ; If cnt is negative ; Update the cnt ; Increment the ans ; If ans is at most K , then print Yes . Otherwise print No ; Driver Code
function minimumMoves ( s , n , k ) { if ( n & 1 ) { document . write ( " " ) ; return ; } var countOpen = 0 ; var i ; for ( i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == " " ) countOpen ++ ; } var countClose = 0 ; for ( i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == " " ) countClose ++ ; } ; if ( countOpen != countClose ) { document . write ( " " ) ; return ; } var ans = 0 ; var cnt = 0 ; for ( i = 0 ; i < n ; ++ i ) { if ( s [ i ] == ' ' ) ++ cnt ; else { -- cnt ; if ( cnt < 0 ) { cnt = 0 ; ++ ans ; } } } if ( ans <= k ) document . write ( " " ) ; else document . write ( " " ) ; } var S = " " ; var K = 1 ; minimumMoves ( S , S . length , K ) ;