
Expanse of a sequence of length 1 is always 0.
The first line contains a single integer ‘T’ representing the number of test cases. The 'T' test cases follow.
The first line of each test case will contain a single integer ‘N’, representing the size of ‘ARR’
The second line of each test case will contain ‘N’ space-separated integers representing array/list ‘ARR’.
For each test case, print a single integer that represents the sum of the expanse of all subsequences in modulo 10^9+7.
Output for every test case will be printed in a separate line.
You don’t need to print anything, It has already been taken care of. Just implement the given function.
1 <= T <= 50
2 <= N <= 10000
1 <= ARR[i] <= 10^9
Where 'ARR[i]' denotes the 'ith' element of the array.
Time limit: 1 sec
The basic idea is to initialize an integer variable ‘RESULT’: = 0, then we one by one find each subsequence of ‘ARR’ using bit masking and for each subsequence, we add the difference of its maximum and minimum element to ‘RESULT’. Note we do modulo 10^9 + 7 in addition.
The steps are as follows:
The basic idea is to sort the array in non-decreasing order. Then for any two indices ‘i’, ‘j’ (‘i’ < ‘j’) number of subsequences having ARR[i] as a minimum element and ARR[j] as the maximum number will be 2^(j-i-1).
We initialize an integer variable ‘RESULT’: = 0, and for each pair of indices (‘i’, ‘j’) such that ‘j’ > ‘i’, we add (ARR[j] - ARR[i]) * 2^(j-i-1) in ‘RESULT’ (in modulo 10^9+7 ). To optimize it further we precompute power of 2 up to ‘N’ in modulo 10^9+7.
The steps are as follows:
As discussed in the previous approach, we need to find the sum of (ARR[j] - ARR[i]) * 2^(j-i-1) for each pair (i, j) such that ‘j’ > ‘i’. From this we can observe that for any indices ‘i’, we add ARR[i] * 2^(j-i-1) if 0 <= j < i and we subtract ARR[i] * 2^(j-i+1) if ‘N’ > j > i.
For any integer ‘i’, summation of 2^(j-i+1) for all 0 <= j < i, is 2^i -1 and summation of 2^(j-i+1) for all N > j > i is 2^(N-i-1) -1. Thus for each index ‘i’ we should add ARR[i] * (2^i - 2^(N-i-1)) in the final result.
The steps are as follows: