3721. Longest Balanced Subarray II Hard

@problem@discussion
#Array#Hash Table#Divide and Conquer#Segment Tree#Prefix Sum



1/**
2 * [3721] Longest Balanced Subarray II
3 *
4 * You are given an integer array nums.
5 * A <span data-keyword="subarray-nonempty">subarray</span> is called balanced if the number of distinct even numbers in the subarray is equal to the number of distinct odd numbers.
6 * Return the length of the longest balanced subarray.
7 *  
8 * <strong class="example">Example 1:
9 * <div class="example-block">
10 * Input: <span class="example-io">nums = [2,5,4,3]</span>
11 * Output: <span class="example-io">4</span>
12 * Explanation:
13 * 
14 * 	The longest balanced subarray is [2, 5, 4, 3].
15 * 	It has 2 distinct even numbers [2, 4] and 2 distinct odd numbers [5, 3]. Thus, the answer is 4.
16 * </div>
17 * <strong class="example">Example 2:
18 * <div class="example-block">
19 * Input: <span class="example-io">nums = [3,2,2,5,4]</span>
20 * Output: <span class="example-io">5</span>
21 * Explanation:
22 * 
23 * 	The longest balanced subarray is [3, 2, 2, 5, 4].
24 * 	It has 2 distinct even numbers [2, 4] and 2 distinct odd numbers [3, 5]. Thus, the answer is 5.
25 * </div>
26 * <strong class="example">Example 3:
27 * <div class="example-block">
28 * Input: <span class="example-io">nums = [1,2,3,2]</span>
29 * Output: <span class="example-io">3</span>
30 * Explanation:
31 * 
32 * 	The longest balanced subarray is [2, 3, 2].
33 * 	It has 1 distinct even number [2] and 1 distinct odd number [3]. Thus, the answer is 3.
34 * </div>
35 *  
36 * Constraints:
37 * 
38 * 	1 <= nums.length <= 10^5
39 * 	1 <= nums[i] <= 10^5
40 * 
41 */
42pub struct Solution {}
43
44// problem: https://leetcode.com/problems/longest-balanced-subarray-ii/
45// discuss: https://leetcode.com/problems/longest-balanced-subarray-ii/discuss/?currentPage=1&orderBy=most_votes&query=
46
47// submission codes start here
48
49impl Solution {
50    pub fn longest_balanced(nums: Vec<i32>) -> i32 {
51        0
52    }
53}
54
55// submission codes end
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_3721() {
63    }
64}
65

Back
© 2026 bowen.ge All Rights Reserved.