<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [0,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>

#pragma GCC optimize("Ofast","inline","fast-math","unroll-loops","no-stack-protector","-ffast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native","f16c")
int desync = []{
    ios::sync_with_stdio(0);
    cin.tie(0);
    return 0;
}();
class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        vector<int> prefix; prefix.reserve(nums.size());
        prefix.push_back(nums[0] == 0 ? -1 : 1);
        for (int i = 1; i < nums.size(); i++) {
            prefix.push_back(prefix[i-1] + (nums[i] == 0 ? -1 : 1));
        }
        int max_length = 0, n = nums.size()-1;
        for (int i, j = 0, pre_sum = 0; max_length <= n - j; pre_sum = prefix[j++]) {
            for (i = n; max_length <= i - j; ) {
                if (prefix[i] == pre_sum) {
                    max_length = max(max_length, i - j + 1); break;
                }
                int x = prefix[i] - pre_sum;
                i -= abs(x);
            }
        }
        return max_length;
    }
};
85800