Contiguous Array in C++


Suppose we have a binary array, we have to find the maximum length of a contiguous subarray with equal number of 0 and 1. So if the input is like [0,1,0], then the output will be 2 as [0,1] or [1,0] is the largest contiguous array with equal number of 0s and 1s.

To solve this, we will follow these steps −

  • ret := 0, n := size of nums, sum := 0
  • make a map m, set m[0] := - 1
  • for i in range 0 to size of nums – 1
    • sum := sum + 1 when nums[i] is 1 otherwise sum := sum – 1
    • if sum is in m, then ret := max of ret and i – m[sum], otherwise m[sum] := i
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   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

Updated on: 02-May-2020

778 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements