Java 4ms 100% straight-forward counting
Keep track of the number of unmatched open and closed parentheses.\n\n```\npublic int minAddToMakeValid(String S) {\n\tint unmatchedOpen = 0;\n\tint unmatchedCl
Keep track of the number of unmatched open and closed parentheses.\n\n```\npublic int minAddToMakeValid(String S) {\n\tint unmatchedOpen = 0;\n\tint unmatchedClose = 0;\n    \n\tfor (char c : S.toCharArray()) {\n\t\tif (c == \'(\') {\n            unmatchedOpen++;\n        } else if (unmatchedOpen > 0)\n\t\t\tunmatchedOpen--;\n        } else {\n\t\t    // This is a closed paren and there \n\t\t\t// isn\'t an open one to balance it out\n            unmatchedClose++;\n        }\n\t}\n        \n    return unmatchedClose + unmatchedOpen;\n}
[]