![]() |
VOOZH | about |
Given an array of N distinct element of at least size 2. A pair (a, b) in an array is defined as 'a' is the index of second highest element and 'b' is the index of highest element in the array. The task is to count all the distinct pair where a < b in all the subarrays.
Examples :
Input : arr[] = { 1, 3, 2, 4 }
Output : 3
Explanation :
The subarray { 1 }, { 3 }, { 2 }, { 4 } does not contain any such pair
The subarray { 1, 3 }, { 2, 4 } contain (1, 2) as pair
The subarray { 3, 2 } does not contain any such pair
The subarray { 3, 2, 4 } contain (1, 3) as a pair
The subarray { 1, 3, 2 } does not contain any such pair
The subarray { 1, 3, 2, 4 } contain (2, 4) as a pair
So, there are 3 distinct pairs, which are (1, 2), (1, 3) and (2, 4).
Method 1: (Brute Force): Simple approach can be,
Time Complexity: O(n2).
Method 2: (Using stack):
For given array A, suppose for an element at index curr (A[curr]), first element greater than it and after it is A[next] and first element greater than it and before it A[prev]. Observe that for all subarray starting from any index in range [prev + 1, curr] and ending at index next, A[curr] is the second largest and A[next] is the largest, which generate (curr - prev + 1) pairs in total with difference of (next - curr + 1) in maximum and second maximum.
If we get next and prev greater element in an array, and keep track of maximum number of pairs possible for any difference (of largest and second largest). We will need to add all these numbers.
Now only job left is to get greater element (after and before) any element. For this, refer Next Greater Element.
Traverse from the starting element in an array, keeping track of all numbers in the stack in decreasing order. After arriving at any number, pop all elements from stack which are less than current element to get location of number bigger than it and push current element on it. This generates required value for all numbers in the array.
Implementation:
3