![]() |
VOOZH | about |
Given an array arr[]of integers with length N and an integer X, the task is to calculate the number of subarrays with median greater than or equal to the given integer X.
Examples:
Input: N=4, A = [5, 2, 4, 1], X = 4
Output: 7
Explanation: For subarray [5], median is 5. (>= 4)
For subarray [5, 2], median is 5. (>= 4)
For subarray [5, 2, 4], median is 4. (>= 4)
For subarray [5, 2, 4, 1], median is 4. (>= 4)
For subarray [2, 4], median is 4. (>= 4)
For subarray [4], median is 4. (>= 4)
For subarray [4, 1], median is 4. (>= 4)Input: N = [3, 7, 2, 0, 1, 5], X = 10
Output: 0
Explanation: There are no subarrays with median greater than or equal to X.
Approach: The problem can be solved based on the following idea.
To find a subarray with median greater or equal to X at least half of the elements should be greater than or equal to X.
Follow the below steps to implement the above idea:
Note: For efficiently calculating the number of elements with a value less than or equal to Y, use policy-based data structures.
Below is the implementation of the above approach:
7
Time Complexity: O(N * logN)
Auxiliary Space: O(N)