Input: nums = [1,1,1,1,1,1]
Output: 6
Explanation: [1, 1, 1, 1, 1] is the only subsequence of size 5 that can be formed, and it has a unique middle mode of 1. This subsequence can be formed in 6 different ways, so the output is 6.
Example 2:
Input: nums = [1,2,2,3,3,4]
Output: 4
Explanation: [1, 2, 2, 3, 4] and [1, 2, 3, 3, 4] each have a unique middle mode because the number at index 2 has the greatest frequency in the subsequence. [1, 2, 2, 3, 3] does not have a unique middle mode because 2 and 3 appear twice.
Example 3:
Input: nums = [0,1,2,3,4,5,6,7,8]
Output: 0
Explanation:
There is no subsequence of length 5 with a unique middle mode.
classSolution: defsubsequencesWithMiddleMode(self, nums: list[int]) -> int: n = len(nums) right_counts = {num: cnt for num, cnt in Counter(nums).items() if cnt > 1} left_counts = {num: 0for num in right_counts}
MOD = 1_000_000_007 nC2 = lambda n: n * (n - 1) >> 1 total = 0 r = n for l inrange(n - 2): r -= 1 a = nums[l] if a notin right_counts: continue right_counts[a] -= 1
if l > 1: la = left_counts[a] ra = right_counts[a] cnt = nC2(l) * nC2(r) cnt -= nC2(l - la) * nC2(r - ra) for b in right_counts: if b == a: continue lb = left_counts[b] rb = right_counts[b] if lb + rb < 2: continue if la > 0: cnt -= la * lb * rb * (r - ra - rb) cnt -= la * (l - la) * nC2(rb) if ra > 0: cnt -= ra * lb * rb * (l - la - lb) cnt -= ra * (r - ra) * nC2(lb) total = (total + cnt) % MOD
classSolution: defsubsequencesWithMiddleMode(self, nums: list[int]) -> int: n = len(nums) right_counts = {num: cnt for num, cnt in Counter(nums).items() if cnt > 1} left_counts = {num: 0for num in right_counts}
MOD = 1_000_000_007 nC2 = lambda n: n * (n - 1) >> 1
sum_l_r = 0# \sum_b{l_b ⋅ r_b} sum_l_r2 = 0# \sum_b{l_b ⋅ r_b^2} sum_l2_r = 0# \sum_b{l_b^2 ⋅ r_b} sum_l2_l = 0# \sum_b{l_b^2 - l_b} sum_r2_r = sum(r * r - r for r in right_counts.values()) # \sum_b{r_b^2 - r_b}
total = 0 r = n for l inrange(n - 2): r -= 1 a = nums[l] if a notin right_counts: continue
la = left_counts[a] ra = right_counts[a] sum_l_r -= la * ra sum_l_r2 -= la * ra * ra sum_l2_r -= la * la * ra sum_l2_l -= la * la - la sum_r2_r -= ra * ra - ra
right_counts[a] -= 1 ra -= 1
if l > 1: cnt = nC2(l) * nC2(r) cnt -= nC2(l - la) * nC2(r - ra) cnt -= sum_l_r * (r * la + l * ra - 2 * la * ra) - sum_l_r2 * la - sum_l2_r * ra cnt -= (sum_l2_l * (r - ra) * ra + sum_r2_r * (l - la) * la) >> 1 total = (total + cnt) % MOD
left_counts[a] += 1 la += 1
sum_l_r += la * ra sum_l_r2 += la * ra * ra sum_l2_r += la * la * ra sum_l2_l += la * la - la sum_r2_r += ra * ra - ra