You are given an array ‘ARR’ containing ‘N’ integers’. The task is to find the sum of the minimum value in ‘SUB’, where ‘SUB’ ranges over every contiguous subarray of ‘ARR.
Example:‘ARR = [3, 2, 1, 3]’, ‘N = 4’
1. Subarrays with ‘1’ as their minimum value: [1], [2,1], [1,3], [3,2,1], [2,1,3], [3,2,1,3]. Sum = 1 + 1 + 1 + 1 + 1 + 1 = 6.
2. Subarrays with ‘2’ as their minimum value: [2], [3,2]. Sum = 2 + 2 = 4.
3. Subarrays with ‘3’ as their minimum value: [3], [3]. Sum = 3 + 3 = 6.
The sum over all subarrays is ‘6 + 4 + 6 = 16’. Thus, you should return ‘16’ as the answer.
Note :
1. The answer may be huge, so return the answer modulo ‘10^9 + 7’.
2. You do not need to print anything; it has already been taken care of. Just implement the function.
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.
The first line of each test case contains an integer ‘N’ denoting the size of the array ‘ARR’.
The second line of each test case contains ‘N’ integers representing the array ‘ARR’.
For more clarity, please refer to the sample inputs.
Output format :
For every test case, you should return the sum of the minimum value in ‘SUB’, where ‘SUB’ ranges over every contiguous subarray of ‘ARR.
1 <= T <= 100
1 <= N <= 1000
1 <= Value in each element of ‘ARR’ <= 10^5
Where ‘T’ is the number of test cases, and ‘N’ is the size of the array ‘ARR’.
Time limit: 1 second
2
4
1 2 3 4
4
2 4 4 2
20
26
Test Case 1 :
1. Subarrays with ‘1’ as their minimum value: [1], [1,2], [1,2,3], [1,2,3,4]. Sum = 1 + 1 + 1 + 1 = 4.
2. Subarrays with ‘2’ as their minimum value: [2], [2,3], [2,3,4]. Sum = 2 + 2 + 2 = 6.
3. Subarrays with ‘3’ as their minimum value: [3], [3,4]. Sum = 3 + 3 = 6.
4. Subarrays with ‘4’ as their minimum value: [4]. Sum = 4.
The sum over all subarrays is ‘4 + 6 + 6 + 4 = 20’. Thus, you should return ‘20’ as the answer.
Test Case 2 :
1. Subarrays with ‘2’ as their minimum value: [2], [2], [2,4], [4,2], [2,4,4], [4,4,2], [2,4,4,2]. Sum = 2 + 2 + 2 + 2 + 2 + 2 + 2 = 14.
2. Subarrays with ‘4’ as their minimum value: [4], [4], [4,4]. Sum = 4 + 4 + 4 = 12.
The sum over all subarrays is ‘14 + 12 = 26’. Thus, you should return ‘26’ as the answer.
2
5
1 3 2 4 2
4
2 1 3 2
28
15
Try to generate all possible subarrays.
A simple approach is to use two nested loops to generate all the possible subarrays. We can use a variable local to the outer loop to track the minimum values of the subarrays generated in the inner loop.
Algorithm:
O(N^2), where ‘N’ is the size of the array ‘ARR’.
We iterate through all subarrays, and there are ‘N*(N+1)/2’ subarrays. Thus, the time complexity is ‘O(N^2)’.
O(1),
Since we are not using any extra space, space complexity is constant.