<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>

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        vector<int> onePos;
        for (int i = 0; i < nums.size(); i ++) if (nums[i]) onePos.push_back(i);
        if (onePos.size() <= 1) return 2 * onePos.size() * (int) (onePos.size() != nums.size());
        else {
            for (int size = onePos.size(); size > 1; size--){
                int first = 0;
                int last = size-1;
                int zeroSpace = onePos[last] - onePos[first] - (last - first);
                int zeroEnds = onePos[first];
           
                while (last < onePos.size()){
                    if (last == onePos.size()-1) zeroEnds += nums.size() - onePos[last] - 1;
                    else zeroEnds += onePos[last+1] - onePos[last] - 1;


                    if (zeroSpace <= size && zeroSpace + zeroEnds >= size){
                        return (2 * size);
                    }
                    else{
                        if (first == 0) zeroEnds -= onePos[first];
                        else zeroEnds -= (onePos[first] - onePos[first-1]-1);
                        zeroSpace += zeroEnds;
                        
                        first++;

                        zeroEnds = (onePos[first] - onePos[first-1]-1);
                        zeroSpace -= zeroEnds;

                        last++;

                        

                    }
                }
            }
            if (onePos.size() == nums.size()) return 0;
            else return 2;
            
        }
    }
};
86600