Today we will read on this article – Contiguous Array in C ++: If we have a binary array, then we need to find the maximum length of a contiguous subs with the same number of 0’s and 1’s. If the input is like [0,1, 0], then the output will be as 2 [0,1] or [1,0] is the largest contiguous array with a number equal to 0 and 1s.
Example
#include <bits/stdc++.h> using namespace std; class program { public: int findMaxLength(vector<int>& nums) { int ret = 0; int n = nums.size(); int sum = 0; map <int, int> m; m[0] = -1; for(int i = 0; i < nums.size(); i++){ sum += nums[i] == 1 ? 1: -1; if(m.count(sum)){ ret = max(ret, i - m[sum]); }else m[sum] = i; } return ret; } }; main(){ vector<int> v = {0,1,0,0,1}; Solution ob; cout << (ob.findMaxLength(v)); }
Input
[0,1,0,0,1]
Output
4