You are given an array/list ‘arr’ of size ‘n’. Your task is to find the maximum product possible by taking any subset of the array/list ‘arr’.
Since the product can be large, return it modulo 10^9+7
For example:Let arr=[-1,-1,-2,4,3]
We can take the subset {-1,-2,4,3} which will have the product as 24. We can verify that this is the largest product possible. Hence we return 24.
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test cases follow.
The first line of each test case contains ‘n’ denoting the number of elements in arr.
The second line of each test case contains ‘n’ space-separated integers denoting the elements of ‘arr’
Output Format
For each test case, return an integer with the product of the subset with the largest product.
Output for each test case will be printed in a separate line.
Note:
1. You do not need to print anything; it has already been taken care of. Just implement the given function.
2. It is guaranteed that the maximum product will be less than or equal to 10^18.
1 <= T <= 50
1 <= N <= 10^4
-10^2 <= arr[i] <=10^2
Where ‘T’ is the total number of test cases and N denotes the size of arr1 and arr[i] represents the value of any number in arr
Time limit: 1 second
2
6
-3 -3 -6 -1 -5 2
6
1 2 9 -90 6 4
540
432
Test Case 1:
In the first test case, we will take the numbers {-3,-3,-6,-5,2} whose product is 540. We can verify that out of all possible subsets; this is the maximum product subset.
Test Case 2:
In the second test case, we will take {1,2,9,6,4} whose product is 432.
2
4
0 1 0 -1
4
2 4 9 8
1
576
We can include every positive number in the product and may exclude one negative number if their count is odd.
The key idea in solving this problem is to realize that the product of positive numbers is always increasing. Also, the product of even numbers of negatives also increases our result.
So, we can conclude all the points as :
Note that in the case of an odd number of negative numbers, there can be multiple elements whose magnitude is the least but we need to exclude only one of them.
Algorithm:
O(n), where n is the number of elements in the array.
We need to traverse the array once to find the maximum product. Hence the complexity is in order of n.
O(1) we are using constant space.
As we are using constant space, hence space complexity is O(1)