# 921. Minimum Add to Make Parentheses Valid

由()组成的字符串，问最少添加多少个(或)能使所有()配对。()配对问题和301类似，遇到(+1)-1当值为负时说明(缺，需要res+1，并重置值为0。当最后值为正时说明(多，因为只要返回需要增加的值而不是找具体的位置，无需向301一样再反着遍历一遍，直接让值和res相加即结果。

```
/*
 * @lc app=leetcode id=921 lang=cpp
 *
 * [921] Minimum Add to Make Parentheses Valid
 */

// @lc code=start
class Solution {
public:
    int minAddToMakeValid(string S) {
        const int N = S.length();
        int res = 0, c = 0;
        for (int i = 0; i < N; ++i) {
            if (S[i] == '(') ++c;
            else --c;
            if (c < 0) {
                ++res;
                ++c;
            }
        }
        return res + c;
    }
};
// @lc code=end


```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/exhaustive-search/remove-invalid-parentheses/921.-minimum-add-to-make-parentheses-valid.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
