Longest Harmonious Subsequence

Last Updated: 14 Mar, 2021
Difficulty: Hard

PROBLEM STATEMENT

A sequence is Harmonious if the difference between the maximum and the minimum of all the elements is exactly 1.

For example
``````[3, 4, 3, 3, 3, 3, 4] is a harmonic array as the maximum of all the elements is 4 and minimum of all the elements is 3. So, the difference between the maximum and the minimum = 4 - 3 = 1.
``````
Input Format:
``````The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.

The first line of each test case contains an integer N, which denotes the number of integers in the array ‘ARR’.

The second line of each test case contains 'N' integers of the array ‘ARR’, separated by space.
``````
Output Format:
``````For each test case, return the size of the longest harmonious subsequence.
``````
Note:
``````You are not required to print the expected output; it has already been taken care of. Just implement the function.
``````
Constraints:
``````1<= T <= 100
1 <= N <= 10^4
1 <= ARR[i] <= 10^8

Time Limit: 1 sec
``````

Approach 1

The idea is to generate all the possible subsequences using the bit masking technique. For each subsequence, check if it is a Harmonious subsequence or not. Take the maximum length of all the possible subsequences.

The steps are as follows:

• Initialize 'ANSWER' to 0, which denotes the longest length of the Harmonic subsequence.
• Iterate from ‘i’ = 0 to ‘2^N - 1’, where ‘N’ is the length of the given Array, ‘ARR’.
• Initialize three integers ‘MIN_VALUE’, ‘MAX_VALUE’, and ‘COUNT_LENGTH’ with INT_MAX, INT_MIN, and 0 respectively which stores the minimum, maximum values of the current subsequence and length of the current subsequence respectively.
• Iterate from ‘j’ = 0 to ‘N-1’:
• If a jth bit of i is set and ‘MIN_VALUE’ is less than ARR[j], then update ‘MIN_VALUE’ to ARR[j].
• If a jth bit of i is set and ‘MAX_VALUE’ is greater than ARR[j], then update ‘MAX_VALUE’ to ARR[j].
• Increment the count as we are including the current element in the subsequence.
• If the difference between the ‘MAX_VALUE’ and ‘MIN_VALUE’ is 1. It means it is a valid subsequence. Update 'ANSWER' to a maximum of 'ANSWER' and ‘COUNT_LENGTH’. Also, take care of the integer overflow.