|
1 | 1 | // https://leetcode.com/problems/longest-harmonious-subsequence
|
2 |
| -// |
| 2 | +// |
3 | 3 | // We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.
|
4 |
| -// |
| 4 | +// |
5 | 5 | // Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.
|
6 |
| -// |
| 6 | +// |
7 | 7 | // A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
|
8 |
| -// |
| 8 | +// |
9 | 9 | // **Example 1:**
|
10 |
| -// |
| 10 | +// |
11 | 11 | // ```
|
12 | 12 | // **Input:** nums = [1,3,2,2,5,2,3,7]
|
13 | 13 | // **Output:** 5
|
14 | 14 | // **Explanation:** The longest harmonious subsequence is [3,2,2,2,3].
|
15 | 15 | // ```
|
16 |
| -// |
| 16 | +// |
17 | 17 | // **Example 2:**
|
18 |
| -// |
| 18 | +// |
19 | 19 | // ```
|
20 | 20 | // **Input:** nums = [1,2,3,4]
|
21 | 21 | // **Output:** 2
|
22 | 22 | // ```
|
23 |
| -// |
| 23 | +// |
24 | 24 | // **Example 3:**
|
25 |
| -// |
| 25 | +// |
26 | 26 | // ```
|
27 | 27 | // **Input:** nums = [1,1,1,1]
|
28 | 28 | // **Output:** 0
|
29 | 29 | // ```
|
30 |
| -// |
| 30 | +// |
31 | 31 | // **Constraints:**
|
32 |
| -// |
| 32 | +// |
33 | 33 | // * `1 <= nums.length <= 2 * 10<sup>4</sup>`
|
34 | 34 | // * `-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>`
|
35 | 35 |
|
36 | 36 | pub fn find_lhs(nums: Vec<i32>) -> i32 {
|
37 |
| - |
| 37 | + let nums_map = nums |
| 38 | + .iter() |
| 39 | + .fold(std::collections::HashMap::new(), |mut acc, &x| { |
| 40 | + *acc.entry(x).or_insert(0) += 1; |
| 41 | + acc |
| 42 | + }); |
| 43 | + let mut res = 0; |
| 44 | + for (&k, &v) in &nums_map { |
| 45 | + if let Some(&v2) = nums_map.get(&(k + 1)) { |
| 46 | + res = std::cmp::max(res, v + v2); |
| 47 | + } |
38 | 48 | }
|
| 49 | + return res; |
| 50 | +} |
39 | 51 |
|
40 | 52 | #[test]
|
41 | 53 | pub fn t1() {
|
| 54 | + assert_eq!(find_lhs(vec![1, 3, 2, 2, 5, 2, 3, 7]), 5); |
42 | 55 | }
|
0 commit comments