Problem of the day
You are given an array ‘ARR’ consist of ‘N’ positive integers, and a positive integer ‘K’.
Your task is to count and return the number of contiguous subarrays having products of their elements strictly less than ‘K’.
Example:
Consider an array ARR = [1, 2, 3, 4, 5], and K = 7, then all the subarrays having product less than 7 are [1], [2], [3], [4], [5], [1, 2], [2,3], [1,2,3] i.e there is total 8 subarays having product less than 7.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next 2*T lines represent the ‘T’ test cases.
The first line contains two space-separated integers ‘N’ and ‘K’ respectively.
The second line contains ‘N’ space-separated positive integers denoting the array ‘ARR’.
Output format :
For each test case, print a single line containing a single integer denoting integer representing the count of the number of contiguous subarrays having products of their elements strictly less than ‘K’.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10 ^ 4
1 <= K <= 10 ^ 8
1 <= ARR[i] <= 10 ^ 4
Where ‘T’ is the total number of test cases, ‘N’ is the number of elements in the given array ‘Arr’, ‘K’ is the given integer, and ‘ARR[i]’ is the element of the given array ‘ARR’.
Time limit: 1 sec
2
1 7
7
5 7
1 2 3 4 5
0
8
Test case 1:
There is only one element in ‘ARR’ i.e 7, so it has only one subarray i.e [7]. The product of all elements of this subarray will be 7 which is equal to 7, thus there is no subarray having product strictly less than 7
Test case 2:
See the problem statement for an explanation.
2
5 100
1 2 3 4 5
2 10
10 9
13
1
Find the product of each subarray.
In this approach, we will one by one find the product of each subarray and increment the counter by ‘1’ if we find the subarray having the product of its elements less than ‘K’.
Algorithm
Note that you may need to take care of integer overflow in this approach.
O(N ^ 2), where ‘N’ is the number of elements in the given array ‘ARR’
In the worst-case both inner and outer loops run ‘N’ times, Thus overall time complexity will be O(N ^ 2).
O(1).
We are using constant extra space here.