Problem Statement in English
You are given a 0-indexed integer array nums. A subarray of nums is called balanced if the number of even integers in the subarray is equal to the number of odd integers in the subarray.
Return the length of the longest balanced subarray in nums. If there is no balanced subarray, return 0.
Approach
Judging by the constraints, we can easily get away with a brute force approach.
We can iterate through all the subarrays and check if they are balanced or not. If they are balanced, we can update our result.
And we’re done!
Solution in Python
class Solution:
def longestBalanced(self, nums: List[int]) -> int:
N = len(nums)
res = 0
for i in range(N):
evens = set()
odds = set()
for j in range(i, N):
n = nums[j]
if n % 2:
odds.add(n)
else:
evens.add(n)
if len(evens) == len(odds):
res = max(res, j - i + 1)
return res
Complexity
Time: $O(n^2)$
Since we are iterating through all the subarrays.Space: $O(n)$
Since we are storing the even and odd numbers in sets.
And we are done.