![]() |
VOOZH | about |
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right.
Examples:
Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3
Output: 2
Explanation:
The only array elements satisfying the given conditions are:
- 5: Greater than all elements on its left {2} and at least K(= 3) elements on its right {1, 3, 4, 0}
- 7: Greater than all elements on its left {2, 5, 1} and at least K(= 3) elements on its right {3, 4, 0}
Therefore, the count is 2.
Input: A[] = {11, 2, 4, 7, 5, 9, 6, 3}, K = 2
Output: 1
Naive Approach:
The simplest approach to solve the problem is to traverse the array and for each element, traverse all the elements on its left and check if all of them are smaller than it or not and traverse all elements on its right to check if at least K elements are smaller than it or not. For every element satisfying the conditions, increase count. Finally, print the value of count.
2
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach:
The above approach can be further optimized by using Self-Balancing BST. Follow the steps below:
Below is the implementation of the above approach:
2
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Please refer complete article on Count of Array elements greater than all elements on its left and at least K elements on its right for more details!