


A sequence a1, a2, .... an is called an alternating sequence if its elements satisfy one of the following relations : a1 < a2 > a3 < a4 > a5..... or a1 > a2 < a3 > a4 < a5.
'ARR' = {3, 10, 1, 2, 30}, the longest alternating subsequence for this array can be {3, 10, 1, 30} or {3, 10, 2, 30}. Therefore, the answer will be 4.
The first line of input contains an integer 'T' denoting the number of test cases.
The first line of each test case contains a single integer 'N' representing the length of the array.
The second line of each test case contains 'N' space-separated integers representing the elements of the array 'ARR'.
For each test case, return a single integer which is the length of the longest alternating subsequence.
Print the output of each test case in a separate line.
You don’t have to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 5000
1 <= ARR[i] <= 10^5
Where 'ARR[i]' denotes the ith element of 'ARR'.
Time limit: 1 sec
The idea is to use recursion. Here we have two options that the next element in the sequence should be greater or smaller than the previous element. For this, we will use the indicator to indicate the above condition.
We will declare a function helper and inside it for every element in the array we have -
Call this helper function in the original function twice, one for the indicator as ‘0’ and one for the indicator as ‘1’ and return the maximum of both values.
We are solving this problem by solving its subproblems and then combining the solutions of those subproblems. If we analyze carefully, we will see that we are solving the same subproblems multiple times. Thus, this problem exhibits overlapping subproblems. Thus, in this approach, we will eliminate the need for solving the same subproblems again and again. The idea is to store the answer till the current index and use it for further calls.
Whenever a call is made to the solved subproblem, we will directly return the answer of that subproblem stored in the array.
The helper function:-
We are solving this problem by solving its subproblems and then combining the solutions of those subproblems. If we analyze carefully, we will see that we are solving the same subproblems multiple times. Thus, this problem exhibits overlapping subproblems. Thus, in this approach, we will eliminate the need for solving the same subproblems again and again. The idea is to store the answer till the current index and use it for further calls.
The idea is to solve it without using the extra space in the previous approaches. We were storing the length of the longest alternating subsequence till the index ‘i’ and considering the case that whether the last element is smaller or greater than the previous one.