Description
You are given an integer array nums.
A subarray is called balanced if the number of distinct even numbers in the subarray is equal to the number of distinct odd numbers.
Return the length of the longest balanced subarray.
Example 1:
Input: nums = [2,5,4,3]
Output: 4
Explanation:
- The longest balanced subarray is
[2, 5, 4, 3]. - It has 2 distinct even numbers
[2, 4]and 2 distinct odd numbers[5, 3]. Thus, the answer is 4.
Example 2:
Input: nums = [3,2,2,5,4]
Output: 5
Explanation:
- The longest balanced subarray is
[3, 2, 2, 5, 4]. - It has 2 distinct even numbers
[2, 4]and 2 distinct odd numbers[3, 5]. Thus, the answer is 5.
Example 3:
Input: nums = [1,2,3,2]
Output: 3
Explanation:
- The longest balanced subarray is
[2, 3, 2]. - It has 1 distinct even number
[2]and 1 distinct odd number[3]. Thus, the answer is 3.
Constraints:
1 <= nums.length <= 15001 <= nums[i] <= 105
Solutions
This code appears to find the longest balanced subsequence in an array of numbers. The function iterates through each position in the array (i from 0 to n), and for each starting position, it creates two Sets — odd and even — to track which numbers (or positions) fall into each category. The algorithm then likely continues from each starting point, adding numbers to these sets and checking if a "balanced" condition is met (presumably when the odd and even sets have some equivalent property). The variable res stores the maximum length found throughout all starting positions. This is a brute-force approach that tries every possible subsequence to find which one maintains the best balance according to the problem's definition.
/**
* @param {number[]} nums
* @return {number}
*/
var longestBalanced = function(nums) {
const n = nums.length;
let res = 0;
for (let i = 0; i < n; i++) {
const odd = new Set();
const even = new Set();
for (let j = i; j < n; j++) {
if (nums[j] & 1) {
odd.add(nums[j]);
} else {
even.add(nums[j]);
}
if (odd.size === even.size) {
res = Math.max(res, j - i + 1);
}
}
}
return res;
};