


A sequence 'A' is a subsequence of a sequence 'B' if 'A' can be obtained from 'B' by deletion of several (possibly, zero) elements. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].
The first line of each test case contains an Integer 'N' denoting the size of the array.
The second line of each test case contains 'N' space-separated integers denoting the elements of the array.
Print the length of the longest subsequence such that each adjacent elements of the subsequence have at least one digit in common.
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
1 <= N <= 10 ^ 5
1 <= Arr[i] <= 10 ^ 9
Where Arr[i] is the i-th element in the array.
Time Limit: 1sec
We will write an iterative DP similar to LIS where dp[i] denotes the length of the longest subsequence ending at ‘i’th element.
dp[i] = max(dp[i], dp[j] + 1)
5. Update the maxLength with:
maxLength = max(maxLength, dp[i])
3. Return the maxLength.
We will write an iterative DP of size N*10 where dp[i][j] denotes the length of the longest subsequence till ‘i’ elements having the last element-containing ‘j’ as a digit.
currentMax = max(currentMax, dp[i-1][d] + 1)
4.Update the DP Matrix, for j=0 to j=9:
1. If ‘j’th digit appead in ‘i’th element then we should update it with our calculated currentMax:
dp[i][j] = currentMax
2. Else:
dp[i][j] = dp[i-1][j]
3. Finally Initialize the maxLength = 0.
4. Iterate over i= 0 to i =9 maximizing maxLength:
maxLength = max(maxLenght, dp[n][i])
5. Return maxLength.
We will write an iterative Dynamic Programming Approach with DP array of size 10 where dp[i] denotes the length of longest subsequence having the last element containing ‘i’ as a digit.
currentMax = max(currentMax, dp[d] + 1
4. Update the DP array, for j=0 to j=9:
1. If ‘j’th digit appead in ‘i’th element then we should update it with our calculated currentMax:
dp[j] = currentMax
5. Update the maxLength:
maxLength = max(maxLength, currentMax)
4. Return the maxLength.