Leetcode 957 Solution

This article provides solution to leetcode question 957 (minimum-add-to-make-parentheses-valid)

https://leetcode.com/problems/minimum-add-to-make-parentheses-valid

Solution

class Solution:
    def minAddToMakeValid(self, s: str) -> int:
        cnt = 0
        ans = 0
        for ch in s:
            if ch == '(':
                cnt += 1
            else:
                cnt -= 1
            ans = max(ans, -cnt)

        return ans + (cnt + ans)