1541. Minimum Insertions to Balance a Parentheses String!

class Solution {
    public int minInsertions(String s) {
        int result = 0;
        int need = 0;
        for(int i =0; i<s.length(); i++){
            if(s.charAt(i)=='('){
                //if see '(', it means need to summarize previous need
                // and if need is odd,
                // summarize it, and move one need to certain (result)
                if(need%2==1){
                    need--;
                    result++;
                }
                need+=2;
            }else{// see ')'
                if(need>0){
                    need--;
                }else{
                    result++;
                    need++;
                }
            }
        }
        return result+need;
    }
}

Last updated