You are given an array ‘ARR’ of size ‘N’. Your task is to find a subsequence ‘S’ of ‘ARR’ such that the following conditions hold true:
• ‘S’ must be in arithmetic progression.
• The length of ‘S’ must be the maximum possible.
Return the maximum possible length of 'S'.
Example -
ARR = [2,8,4,13,6] The longest subsequence that is possible here is [2,4,6] which has length '3'.
The first line of input contains an integer 'T' representing the number of test cases.
The first line of each test case contains a single 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.
Output Format:
For each test case, return the length of the longest possible subsequence of the array that is in arithmetic progression.
The output of each test case will be printed in a separate line.
1 <= T <= 5
1 <= N <= 50
1 <= ARR[i] <= 50
Where 'ARR[i]' is element of array at index 'i'.
Time limit: 1 sec
2
4
1 2 3 4
3
1 5 6
4
2
In test case 1,
Given arr = [1, 2, 3, 4]
Longest AP = [1, 2, 3, 4]
So the length of the longest possible AP is 4.
Test Case 2 :
Given arr = [1, 5, 6]
Longest AP = [1, 5]
So the length of the longest possible AP is 2.
2
4
1 2 10 3
2
1 2
3
2
Test Case 1 :
Given arr = [1, 2, 10, 3]
Longest AP = [1, 2, 3]
So the length of the longest possible AP is 3.
Test Case 2 :
Given arr = [1, 2]
Longest AP = [1, 2]
So the length of the longest possible AP is 2.
Can you check all possible common differences that a subsequence can have?.
The idea here is to check all possible common differences that a subsequence can have. We will generate all possible common differences by running two loops then we will try to find the longest subsequence using the current common difference and recursion.
The steps are as follows:
Description of ‘findAP’ function:
This function will take three parameters :
int findAP('INDEX', ‘DIFFERENCE’, ‘ARR’):
O(N ^ N), where ‘N’ is the total number of elements in the array.
Since we need to check all possible differences and our ‘getAP’ function takes O(N ^ N) time as at each step we are making O(N) recursive calls. Thus the time complexity will be O(N ^ N).
O(N), where ‘N’ is the total number of elements in the array.
Since our ‘findAP’ function requires O(N) space in the form of recursive stack space. THus the space complexity will be O(N).