#594
Easy Algorithms Longest harmonious subsequence
Array Hash Table Sliding Window Sorting Counting
64.4% acceptance
Jan 13, 2026
2822
351
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_lhs(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
let mut freq: HashMap<i32, i32> = HashMap::new();
for &x in &nums { *freq.entry(x).or_insert(0) += 1; }
freq.keys().map(|&k| {
if let Some(&v) = freq.get(&(k + 1)) { freq[&k] + v } else { 0 }
}).max().unwrap_or(0)
}
}