---
# System prepended metadata

title: 0921. Minimum Add to Make Parentheses Valid
tags: [Leetcode, Parentheses, Medium]

---

# 0921. Minimum Add to Make Parentheses Valid
###### tags: `Leetcode` `Medium` `Parentheses` 
Link: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/

## 思路
可以参考 [1249. Minimum Remove to Make Valid Parentheses](https://hackmd.io/bQqvjRSvQZq1snaqqSgEDQ) 的思路
用余量记录字符串是否平衡
碰到"("，left+1
碰到")"，left>0,则代表前面有可以配对的"(", 则left-1
        如果left=0，则代表前面少一个"(", 这时给ans+1，说明要补一个")",不改变left
        
## Code
```java=
class Solution {
    public int minAddToMakeValid(String s) {
        int ans = 0;
        int left = 0;
        int n = s.length();
        for(int i=0; i<n; i++){
            if(s.charAt(i)=='(') left++;
            else{
                if(left==0) ans++;
                else left--;
            }
        }
        ans += left;
        return ans;
    }
}
```