Problem Description
Given an integer array, a harmonious array is defined as one in which the difference between its maximum and minimum values is exactly 1. The task is to find the length of the longest harmonious subsequence among all its possible subsequences.
Key Insights
- Use a frequency table (hash map) to count the occurrences of each number.
- For each unique number, check if its complement (number + 1) exists in the frequency table.
- The potential harmonious subsequence length for a number is the sum of the count of that number and the count of (number + 1).
- Track the maximum length obtained from the above sum; return 0 if no harmonious subsequence exists.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array, because we iterate through the array to build the frequency table and then iterate through the keys of the table. Space Complexity: O(n) in the worst case when all elements are unique, as we need to store counts for each element.
Solution
We solve the problem by first counting the frequency of each number in the array using a hash table. Then, iterate over each unique number and check if (number + 1) is present in the map. If found, add the two counts, and update the result if this sum is greater than the current record. This approach avoids unnecessary checks and leverages constant time access of hash tables.