3960. Frequency Balance Subarray
Description
You are given an integer array nums.
Define a frequency balance subarray as follows:
- If the subarray contains only one distinct value, it is frequency balanced.
- Otherwise, there must exist a positive integer
fsuch that every distinct value in the subarray occurs eitherfor2 * ftimes, and both frequencies occur among the distinct values.
Return an integer denoting the length of the longest frequency balance subarray.
Example 1:
Input: nums = [1,2,2,1,2,3,3,3]
Output: 5
Explanation:
- The longest frequency balance subarray is
[2, 1, 2, 3, 3]. - The elements that appear most frequently are 2 and 3, both appearing twice.
- The remaining element 1 appears once, meeting the requirements.
Example 2:
Input: nums = [5,5,5,5]
Output: 4
Explanation:
- The longest frequency balance subarray is
[5, 5, 5, 5]. - The element that appears most frequently is 5.
- There are no other elements meeting the requirements.
Example 3:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
Since all elements appear only once, the length of the longest frequency balance subarray is 1.
Constraints:
1 <= nums.length <= 1031 <= nums[i] <= 109
Solutions
Solution 1: Enumeration + Hash Table
Thinking
\(n\le 10^3\), so enumerating both ends in \(O(n^2)\) is acceptable. Balance means either a single value, or exactly two values whose frequencies are in ratio \(2:1\).
Fix \(l\) and extend \(r\), keeping value counts in \(\textit{cnt}\) and “how many values have this frequency” in \(\textit{freq}\). Each extension checks the two shapes in \(O(1)\) and updates the longest length.
We can enumerate the left endpoint \(l\) of the subarray in the range \([0, n)\), then enumerate the right endpoint \(r\) from left to right starting from \(l\). During the enumeration, we use two hash tables \(\textit{cnt}\) and \(\textit{freq}\) to record the frequency of each element in the subarray and the frequency of each frequency value, respectively.
When either of the following conditions is satisfied, update the answer \(\textit{ans} = \max(\textit{ans}, r - l + 1)\):
- There is only one distinct element in the hash table \(\textit{cnt}\), i.e., the length of \(\textit{cnt}\) is \(1\);
- There are only two distinct frequency values in the hash table \(\textit{freq}\), i.e., the length of \(\textit{freq}\) is \(2\), and one frequency value is exactly twice the other;
After the enumeration ends, return the answer \(\textit{ans}\).
The time complexity is \(O(n^2)\) and the space complexity is \(O(n)\). Where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |