|
| 1 | +# 1224. Maximum Equal Frequency |
| 2 | +Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. |
| 3 | + |
| 4 | +If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). |
| 5 | + |
| 6 | +#### Example 1: |
| 7 | +<pre> |
| 8 | +<strong>Input:</strong> nums = [2,2,1,1,5,3,3,5] |
| 9 | +<strong>Output:</strong> 7 |
| 10 | +<strong>Explanation:</strong> For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. |
| 11 | +</pre> |
| 12 | + |
| 13 | +#### Example 2: |
| 14 | +<pre> |
| 15 | +<strong>Input:</strong> nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] |
| 16 | +<strong>Output:</strong> 13 |
| 17 | +</pre> |
| 18 | + |
| 19 | +#### Constraints: |
| 20 | +* <code>2 <= nums.length <= 10<sup>5</sup></code> |
| 21 | +* <code>1 <= nums[i] <= 10<sup>5</sup></code> |
| 22 | + |
| 23 | +## Solutions (Rust) |
| 24 | + |
| 25 | +### 1. Solution |
| 26 | +```Rust |
| 27 | +use std::collections::HashMap; |
| 28 | + |
| 29 | +impl Solution { |
| 30 | + pub fn max_equal_freq(nums: Vec<i32>) -> i32 { |
| 31 | + let mut count_nums = HashMap::new(); |
| 32 | + let mut count_ocurrences = HashMap::new(); |
| 33 | + |
| 34 | + for &num in &nums { |
| 35 | + *count_nums.entry(num).or_insert(0) += 1; |
| 36 | + } |
| 37 | + for &ocurrence in count_nums.values() { |
| 38 | + *count_ocurrences.entry(ocurrence).or_insert(0) += 1; |
| 39 | + } |
| 40 | + |
| 41 | + for i in (0..nums.len()).rev() { |
| 42 | + if count_ocurrences.len() == 1 { |
| 43 | + let (&k0, &v0) = count_ocurrences.iter().next().unwrap(); |
| 44 | + |
| 45 | + if k0 == 1 || v0 == 1 { |
| 46 | + return i as i32 + 1; |
| 47 | + } |
| 48 | + } else if count_ocurrences.len() == 2 { |
| 49 | + let (&k0, &v0) = count_ocurrences.iter().max().unwrap(); |
| 50 | + let (&k1, &v1) = count_ocurrences.iter().min().unwrap(); |
| 51 | + |
| 52 | + if (k1, v1) == (1, 1) || (k0 == k1 + 1 && v0 == 1) { |
| 53 | + return i as i32 + 1; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + *count_ocurrences.get_mut(&count_nums[&nums[i]]).unwrap() -= 1; |
| 58 | + if count_ocurrences.get(&(count_nums[&nums[i]])) == Some(&0) { |
| 59 | + count_ocurrences.remove(&count_nums[&nums[i]]); |
| 60 | + } |
| 61 | + *count_nums.get_mut(&nums[i]).unwrap() -= 1; |
| 62 | + if count_nums[&nums[i]] > 0 { |
| 63 | + *count_ocurrences.entry(count_nums[&nums[i]]).or_insert(0) += 1; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + 1 |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments