Sunday, April 25, 2021

525. Contiguous Array

 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:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.

class Solution {
public:
    
    int findMaxLength(vector<int>& nums) {
        unordered_map<int, int> mp;
        mp[0] = -1;
        int ans = 0;
        int counter = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 1) {
                counter++;
            } else {
                counter--;
            }
            if (mp.count(counter) != 0) {
                ans = max(ans, i - mp[counter]);
            } else {
                mp[counter] = i;
            }
        }
        return ans;
    }
};

No comments:

Post a Comment