Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements