


Ninja recently studied about subsequences and his teacher gave him the following challenge which no other student was able to solve till now.
You are given an array ‘A’ of size ‘N’ and an integer ‘K’. You find all the subsequences of size ‘K’ from the array ‘A’. Now for each of the subsequences, you calculate the product of all elements except the minimum element and the maximum element of the subsequence. After that you need to calculate the product of all these values.
Output the final product calculated by Ninja. Since the answer can be large, output it modulo 10^9+7.
Example :N = 4 , K = 3
A = [ 1, 2, 3, 4 ]
Explanation :
All subsequence of size ‘3’ are :
[ 1, 2, 3 ] : The product is 2.
[ 1, 2, 4 ] : The product is 2.
[ 1, 3, 4 ] : The product is 3.
[ 2, 3, 4 ] : The product is 3.
The final product is 2*2*3*3 = 36.
The first line contains an integer 'T' which denotes the number of test cases to be run. Then the test cases follow.
The first line of each test case contains integers ‘N’ and ‘K’.
The next line contains ‘N’ integers representing the elements of array ‘A’.
Output format :
For each test case, output an integer denoting the required product modulo 10^9+7.
Print the output of each test case in a new line.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
3 <= N <= 5000
3 <= K <= N
1 <= A[i] <= 10^5
Time Limit : 1 sec
2
5 4
1 3 5 2 2
3 3
3 2 4
3456
3
For test case 1 we have,
The subsequences are :
[ 1, 3, 5, 2 ] with product 6.
[ 1, 3, 5, 2 ] with product 6.
[ 1, 3, 2, 2 ] with product 4.
[ 1, 5, 2, 2 ] with product 4.
[ 3, 5, 2, 2 ] with product 6.
Hence, the required product is 6*6*4*4*6 = 3456.
For test case 2 we have,
There is only 1 subsequence :
[ 3, 2, 4 ] with product 3.
Hence, we output 3.
2
4 3
6 5 2 6
5 3
9 7 4 2 10
900
8192
Think about the contribution of each element in the final result.
Approach :
Algorithm :
O( N^2 ) , where ‘N’ is the size of the array ‘A’.
We are calculating all binomial coefficients , so the overall time complexity is O( N^2 ).
O( N^2 ) , where ‘N’ is the size of the array ‘A’.
We are storing all binomial coefficients , so the overall space complexity is O( N^2 ).