Longest Harmonious Subsequence
A harmonious array is one where the difference between the maximum and minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all possible subsequences. A subsequence is a sequence derived by deleting some or no elements without changing the order of the remaining elements.
A brute force approach would generate all 2ⁿ subsequences, which is infeasible. The key insight is that the order of elements does not matter for determining whether a subsequence can be harmonious — we just need to count frequencies. If we have numbers x and x+1 in the array, we can form a harmonious subsequence by taking all occurrences of x and all occurrences of x+1.
This becomes a simple hash map frequency problem: count how many times each number appears. Then for each unique number n, check if n + 1 exists in the map. If so, the candidate length is freq[n] + freq[n + 1]. Track the maximum candidate across all numbers. This runs in O(n) time with O(n) space.
Edge cases include a single element (return 0, since min and max are the same), an array with no adjacent values (return 0), and an array with all same values (return 0 since max - min = 0, not 1).
Example Input & Output
No adjacent numbers exist.
All same, max-min=0 not 1.
Any adjacent pair gives length 2.
Subsequence [3,2,2,2,3] has max-min=1.
Best is [1,1,2,2] or [2,2,3,3].
Algorithm Flow
Solution Approach
Find the longest subsequence where the maximum and minimum values differ by exactly 1. Count the frequency of each number using a hash map. For each number, check if number + 1 also exists. The length of a harmonious subsequence using both numbers is freq[num] + freq[num + 1]. Track the maximum such sum.
Only adjacent values (differing by 1) can form a harmonious subsequence. The sum of their frequencies gives the longest possible subsequence containing both values.
Time complexity is O(n), space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] nums) {
Map<Integer,Integer> freq = new HashMap<>();
for (int n : nums) freq.put(n, freq.getOrDefault(n, 0) + 1);
int best = 0;
for (int n : freq.keySet()) {
if (freq.containsKey(n + 1)) {
best = Math.max(best, freq.get(n) + freq.get(n + 1));
}
}
return best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
