Created
February 10, 2026 22:20
-
-
Save tatsuyax25/a1bbafbbae1269cb656e61d2ed1d3beb to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| */ | |
| var longestBalanced = function(nums) { | |
| const n = nums.length; | |
| let maxLen = 0; | |
| // Fix a starting index i | |
| for (let i = 0; i < n; i++) { | |
| // For each new start, we reset the distinct sets | |
| const evens = new Set(); | |
| const odds = new Set(); | |
| // Extend the subarray to the right: j is the ending index | |
| for (let j = i; j < n; j++) { | |
| const x = nums[j]; | |
| // Track distinct evens and odds in the current subarray nums[i..j] | |
| if (x % 2 === 0) { | |
| evens.add(x); | |
| } else { | |
| odds.add(x); | |
| } | |
| // Check if this subarray is balanced | |
| if (evens.size === odds.size) { | |
| const len = j - i + 1; | |
| if (len > maxLen) { | |
| maxLen = len; | |
| } | |
| } | |
| } | |
| } | |
| return maxLen; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment