You have been an array/list “ARR” of integers. Now, you are supposed to find a subsequence of minimum length such that the sum of elements in the subsequence is strictly greater than the sum of the rest of the elements.
Please note that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements.
Note:
If there are multiple solutions, then find the subsequence with the maximum total sum. Also, assume that there will be a unique solution.
Input Format :
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first input line of each test case contains an integer ‘N’ denoting the number of elements in the given array/list.
The second input line of each test case contains ‘N’ space-separated integers denoting the elements of the “ARR”.
Output Format :
For each test case, print the space-separated integers denoting the elements of the desired subsequence in non-increasing order.
Print the output of each test case in a separate line.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 50
1 <= N <= 10000
1 <= ARR[i] <= 10000
Where ARR[i] denotes the i-th element of the given array/list.
Time limit: 1 sec
2
2
7 11
4
2 3 7 3
11
7 3
For the first test case, subsequence [11] is minimal such that the sum of its elements is strictly greater than the elements not included.
For the second test case, subsequences [7, 3], [2, 7] are minimal such that the sum of their elements are strictly greater than the elements not included. But [7, 3] has the maximum sum so the answer will be [7, 3].
2
1
3
5
4 4 7 6 7
3
7 7 6
For the first test case, subsequence [3] is minimal such that the sum of its elements is strictly greater than the elements not included.
For the second test case, subsequence [7, 6, 7] is the desired subsequence having the sum of its elements strictly greater than the sum of the elements not included.
Can sorting help?
The key idea of this approach is to sort the elements of the given array/list in non-increasing order. Since we are looking for the subsequence having a minimum length such that the sum of its elements is strictly greater than the sum of the rest of the elements, we will choose elements from the front of the sorted array/list greedily. This will ensure that we are selecting the minimum possible elements for getting any sum.
Now, consider the following steps:
O(N * log(N)), where ‘N’ is the length of the given array/list.
Since we are sorting the given array/list which takes O(N * log(N)) and then iterating through it twice which takes O(N) time. So, the overall time complexity will be 2 * O(N) + O(N * log(N)) = O(N * log(N)).
O(N), where ‘N’ is the length of the given array/list.
Since we are storing the subsequence in an array/list where it will contain O(N) elements. So, the overall space complexity will be O(N).