Skip to content

Commit 8d6237c

Browse files
committed
feat: add more
1 parent 2921c79 commit 8d6237c

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,55 @@
11
// https://leetcode.com/problems/longest-harmonious-subsequence
2-
//
2+
//
33
// We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.
4-
//
4+
//
55
// Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.
6-
//
6+
//
77
// 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+
//
99
// **Example 1:**
10-
//
10+
//
1111
// ```
1212
// **Input:** nums = [1,3,2,2,5,2,3,7]
1313
// **Output:** 5
1414
// **Explanation:** The longest harmonious subsequence is [3,2,2,2,3].
1515
// ```
16-
//
16+
//
1717
// **Example 2:**
18-
//
18+
//
1919
// ```
2020
// **Input:** nums = [1,2,3,4]
2121
// **Output:** 2
2222
// ```
23-
//
23+
//
2424
// **Example 3:**
25-
//
25+
//
2626
// ```
2727
// **Input:** nums = [1,1,1,1]
2828
// **Output:** 0
2929
// ```
30-
//
30+
//
3131
// **Constraints:**
32-
//
32+
//
3333
// * `1 <= nums.length <= 2 * 10<sup>4</sup>`
3434
// * `-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>`
3535

3636
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+
}
3848
}
49+
return res;
50+
}
3951

4052
#[test]
4153
pub fn t1() {
54+
assert_eq!(find_lhs(vec![1, 3, 2, 2, 5, 2, 3, 7]), 5);
4255
}

Array/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ mod _0496_next_greater_element_i;
1818
mod _0500_keyboard_row;
1919
mod _0566_reshape_the_matrix;
2020
mod _0575_distribute_candies;
21+
mod _0594_longest_harmonious_subsequence;
2122
mod _0599_minimum_index_sum_of_two_lists;
2223
mod _0661_image_smoother;
2324
mod _0682_baseball_game;

0 commit comments

Comments
 (0)