Count of Subarrays
Given an array of N positive integers a1, a2, ..., an. The value of each contiguous subarray of a given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K.
Input:
The first line contains two space-separated positive integers N and K denoting the size of the array and the value of K. The second line contains N space-separated positive integers denoting the elements of the array.
Output:
Output the number of subarrays having value strictly greater than K.
Constraints:
1 <= T <= 50
1 <= N <= 100
1 <= a[i] <= 105
Example:
Test case: 1
Input:
5 3
3 4 5 2 7
Output:
13
Test case: 2
4 1
1 2 3 4
Output:
9
Explanation:
Test case 1:
All possible subarrays are listed below
with their respective value (maximum in the subarray)
3 -> 3
4 -> 4
5 -> 5
2 -> 2
7 -> 7
3, 4 -> 4
4, 5 -> 5
5, 2 -> 5
2, 7 -> 7
3, 4, 5 -> 5
4, 5, 2 -> 5
5, 2, 7 -> 7
3, 4, 5, 2 -> 5
4, 5, 2, 7 -> 7
3, 4, 5, 2, 7 -> 7
So, number of valid subarrays is 13
Okay, so the strategy is to compute for subarray a[start..end] with help of already computed one a[start..end-1].
Subarray a[start..end] will only make a count if a[start..end-1] already makes a count ( yes because, it's part of the subarray so, anything max in it would be max in the parent one too) Or if a[end]>k.
In both the cases maximum of the subarray, a[start..end] is greater than K
That's what we have done.
Below is illustration for our test case 1,
Input array: [3, 4, 5, 2, 7] and K=3.
So, let's compute the basic test case first
We need a 5X5 DP array for this
Starting to compute for other values.
Len=2
Start=0, end=1
Start=1, end=2
Start=2, end=3
Start=3, end=4
Len=3
Start=0, end=2
Start=1, end=3
Start=2, end=4
Len=4
Start=0, end=3
Start=1, end=4
Len=5
Start=0, end=3
Done!
Count is 13 (count of positive values in the array).
C++ Implementation:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer