Approach
Do it in O(N^2) that count all the even and odd number count in each range [i .. j] with the help of hash, which would only store once for duplicate numbers.
Code
class Solution {
public:
int longestBalanced(vector<int>& nums) {
int n = nums.size();
int maxLen = 0;
for(int i = 0 ; i < n ; ++i) {
unordered_set<int> even;
unordered_set<int> odd;
for(int j = i ; j < n ; ++j) {
if(nums[j] % 2 == 1) odd.insert(nums[j]);
else even.insert(nums[j]);
if(even.size() == odd.size()) maxLen = max(maxLen, j-i+1);
}
}
return maxLen;
}
};