← All problems

525. Contiguous Array

MediumOpen on LeetCodeProblem statement

Problem Statement

525. Contiguous Array

Medium


Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

 

Example 1:

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

Example 2:

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

 

Constraints:

C++

Source file
class Solution {
public:
    int findMaxLength(vector<int>& a) {
        int f=0, ans=0;
        unordered_map<int,int>mp;
        mp[0] = -1;
        for(int i=0; i<a.size(); i++){
            f += a[i]==1 ? 1 : -1;
            if(mp.find(f) == mp.end())
              mp[ f ] = i;
            else
              ans = max(ans, i - mp[f] );
        }
        return ans;
    }
};