Finding the largest subarray with equal number of 0's and 1's

后端 未结 10 1966
我在风中等你
我在风中等你 2020-12-31 11:30

So, I have an array containing only 0\'s and 1\'s. I have to find out the largest subarray containing equal number of 0\'s and 1\'s. One can be a naive approach have complex

10条回答
  •  星月不相逢
    2020-12-31 12:19

    int maxLen(int nums[], int n)
    {   
        unordered_map m;
        m[0] = -1;
        int ans = 0, cur = 0;
        for (int i = 0; i < n; ++i) {
            cur += nums[i] ? 1 : -1;
            if (m.count(cur))
                ans = max(ans, i - m[cur]);
            else
                m[cur] = i;
        }
        return ans;
    }
    

提交回复
热议问题