Given A char array nums, return the maximum length of a contiguous subarray with an equal number of x and y.
Example :
Input : nums = [x ,y ,x ,x ,x] Output : 2 Explanation : [x, y] is the longest contiguous subarray with an equal number of x and y. Input : nums = [x, y, x] Output : 2 Explanation : [x, y] (or [y, x]) is a longest contiguous subarray with equal number of x and y.
Approach :
The basic idea to solve this problem is treat x as -1 & y as +1 calculate sum at every index if the sum is already present in the map then it means there is an subarray with equal x and y .
Implementation :
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// function to return maxlength of subarray
int MaxLength(char nums[], int N)
{
int result = 0, sum = 0;
// to store sum
unordered_map<int, int> mp;
mp[0] = -1;
for (int i = 0; i < N; i++) {
if (nums[i] == 'x') {
sum += -1; // treat x as -1
}
else {
sum += 1; // treat y as 1
}
// chek sum is present in the hashmap
if (mp.find(sum) != mp.end()) {
int length = i - mp[sum];
if (length > result)
result = length;
}
else {
mp[sum] = i;
}
}
// return answer
return result;
}
// Driver code
int main()
{
char nums[] = { 'x', 'y', 'x', 'x' };
int N = sizeof(nums) / sizeof(nums[0]);
cout << MaxLength(nums, N) << endl;
return 0;
}