594. Longest Harmonious Subsequence #1870
-
Topics: We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly Given an integer array Example 1:
Example 2:
Example 3:
Constraints:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the length of the longest harmonious subsequence in an array. A harmonious subsequence is defined as a subsequence where the difference between the maximum and minimum elements is exactly 1. Approach
The key insight here is that any harmonious subsequence can only consist of two distinct numbers that are consecutive integers. By leveraging the frequency map, we efficiently compute the longest such subsequence without explicitly generating all possible subsequences. Let's implement this solution in PHP: 594. Longest Harmonious Subsequence <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function findLHS($nums) {
$freq = array_count_values($nums);
$maxLen = 0;
foreach ($freq as $num => $count) {
$next = $num + 1;
if (isset($freq[$next])) {
$currentLen = $count + $freq[$next];
if ($currentLen > $maxLen) {
$maxLen = $currentLen;
}
}
}
return $maxLen;
}
// Test cases
print_r(findLHS([1, 3, 2, 2, 5, 2, 3, 7])); // Output: 5
print_r(findLHS([1, 2, 3, 4])); // Output: 2
print_r(findLHS([1, 1, 1, 1])); // Output: 0
?> Explanation:
This approach efficiently checks all possible pairs of consecutive numbers in linear time relative to the number of unique elements, making it optimal for large input sizes as specified in the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the length of the longest harmonious subsequence in an array. A harmonious subsequence is defined as a subsequence where the difference between the maximum and minimum elements is exactly 1.
Approach
num + 1
) exists in the map. If it does, the length of the harmonious subsequence formed by these two numbers is the sum of their frequencies.