DP
Problem of the day
You are provided with an array of integers having length ‘N’. All you have to do is to find the number of subsequences of length ‘K’ such that for a particular subsequence Sq[i+1] - Sq[i] should be constant for that complete subsequence.
For Example :‘ARR’ = [1, 3, 8, 5, 13]
‘K’ = 3
Here, the required subsequences are:
[1, 3, 5] => 3 - 1 = 5 - 3 = 2 (constant throughout the subsequence)
[3, 8, 13] => 8 - 3 = 13 - 8 = 5 (constant throughout the subsequence)
Hence, the final answer is 2.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case has two single space-separated integers ‘N’ and ‘K’ representing the length of the array ‘ARR’ and the integer ‘K’ as per the description, respectively.
The second line of each test case has the ‘N’ single space-separated integers representing the elements of the array ‘ARR’.
Output Format :
For each test case, print a single integer representing the total number of subsequences as per the given conditions in the description.
Note :
You don't need to print the output, it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N, K <= 50
0 <= ARR[i] <= 50
Time Limit: 1 sec
1
5 3
1 3 8 5 13
2
For the first test case, the explanation is given in the description.
2
2 2
0 2
2 4
0 10
1
0
Can you think of finding the solution using the concept of the Longest Airthematic Subsequence?
The basic idea here is to find the Airthematic subsequences of length ‘K’ as if Sq[i+1] - Sq[i] is constant for the complete subsequence then it means the subsequence is arithmetic in nature.
Prerequisite:
https://www.codingninjas.com/codestudio/problems/longest-ap_1235209?leftPanelTab=0
The steps are as follows:
Description of ‘findAP’ function:
This function will take six parameters :
void findAP('INDEX', ‘DIFFERENCE’, ‘ARR’, ‘CUR’, ‘K’, ‘ANSWER’):
O(N ^ N), where ‘N’ is the total number of elements in the array ‘ARR’.
Since we need to check all possible differences and our ‘findAP’ 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).