The algorithm works as follow:
def minAddToMakeValid(s: str) -> int:
counter_open, counter_total = 0, 0
for parenthesis in s:
if parenthesis == ")":
# if the counter of available (unclosed) open parenthesis is 0 then we need to add 1 open parenthesis
if counter_open==0:
counter_total += 1
# otherwise just use 1 open parenthesis and decrease the counter by 1
else:
counter_open -= 1
else:
counter_open += 1
return(counter_total + counter_open)