Given an array arr[] of distinct positive elements, the task is to find the number of unique pairs (a, b) such that a is the maximum and b is the second maximum element of some subarray of the given array.
Examples:
Input: arr[] = {1, 2, 3}
Output: 2
{1, 2}, {2, 3}, {1, 2, 3} are the subarrays and the pairs
satisfying given conditions are (2, 1) and (3, 2) only.
Input: arr[] = {4, 1, 2}
Output: 3
Naive approach: We can find pairs for each subarray and store them in a set and then, print them. This approach requires O(n3) time as O(n2) is required for finding the subarrays and O(n) for finding maximum and second maximum element of a subarray.
Efficient approach: Let’s consider a1, a2, a3, a4 be the first four elements of the array and also assume that a2 and a3 are smaller than a1 and a4 is greater than a1.
Clearly, (a4, a1) is one of the required pairs. Now it can be proved that no element after a4 can be paired with a1.
Since all the elements are unique, either there will be an element greater than a4 or all the elements after a4 will be smaller than a4. Let’s assume that aM is greater than a4. Then, the subarray from 1st element till Mth element will have aM as the maximum element and a4 as the second maximum element and hence, (aM, a4) will be the required pair. Now, if all the elements till M are smaller than a4 then a4 will be the maximum element. In any case, a1 will be paired with a4 only.
In simple words, an element will contribute towards a pair if there exists an element greater than this and also having a higher index. The same arguments can be made if the array traversed in the reverse direction.
Hence, total number of pairs = number of elements having a greater element in forward traversal + number of elements having a greater element in backward traversal which can be easily calculated using the approach discussed in this article.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPairs( int arr[], int n)
{
int forward[n] = { 0 };
stack< int > sForward;
for ( int i = 0; i < n; i++) {
while (!sForward.empty()
&& arr[i] > arr[sForward.top()]) {
forward[sForward.top()] = 1;
sForward.pop();
}
sForward.push(i);
}
int backward[n] = { 0 };
stack< int > sBackward;
for ( int i = n - 1; i >= 0; i--) {
while (!sBackward.empty()
&& arr[i] > arr[sBackward.top()]) {
backward[sBackward.top()] = 1;
sBackward.pop();
}
sBackward.push(i);
}
int res = 0;
for ( int i = 0; i < n; i++) {
res += forward[i] + backward[i];
}
return res;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countPairs(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int countPairs( int arr[], int n)
{
int forward[] = new int [n];
Stack<Integer> sForward = new Stack<Integer>();
for ( int i = 0 ; i < n; i++)
{
while (!sForward.empty()
&& arr[i] > arr[(Integer)sForward.peek()])
{
forward[(Integer)sForward.peek()] = 1 ;
sForward.pop();
}
sForward.push(i);
}
int backward [] = new int [n] ;
Stack<Integer> sBackward = new Stack<Integer>() ;
for ( int i = n - 1 ; i >= 0 ; i--)
{
while (!sBackward.empty()
&& arr[i] > arr[(Integer)sBackward.peek()])
{
backward[(Integer)sBackward.peek()] = 1 ;
sBackward.pop();
}
sBackward.push(i);
}
int res = 0 ;
for ( int i = 0 ; i < n; i++)
{
res += forward[i] + backward[i];
}
return res;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 };
int n = arr.length;
System.out.println(countPairs(arr, n));
}
}
|
Python3
def countPairs(arr, n) :
forward = [ 0 ] * n;
sForward = [];
for i in range (n) :
while ( len (sForward) ! = 0 and arr[i] > arr[sForward[ - 1 ]]) :
forward[sForward[ - 1 ]] = 1 ;
sForward.pop();
sForward.append(i);
backward = [ 0 ] * n;
sBackward = [];
for i in range (n - 1 , - 1 , - 1 ) :
while ( len (sBackward) ! = 0 and arr[i] > arr[sBackward[ - 1 ]]) :
backward[sBackward[ - 1 ]] = 1 ;
sBackward.pop();
sBackward.append(i);
res = 0 ;
for i in range (n) :
res + = forward[i] + backward[i];
return res;
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 , 5 ];
n = len (arr);
print (countPairs(arr, n));
|
C#
using System;
using System.Collections;
class GFG
{
static int countPairs( int []arr, int n)
{
int []forward = new int [n];
Stack sForward = new Stack();
for ( int i = 0; i < n; i++)
{
while (sForward.Count != 0
&& arr[i] > arr[( int )sForward.Peek()])
{
forward[( int )sForward.Peek()] = 1;
sForward.Pop();
}
sForward.Push(i);
}
int []backward = new int [n] ;
Stack sBackward = new Stack() ;
for ( int i = n - 1; i >= 0; i--)
{
while (sBackward.Count != 0
&& arr[i] > arr[( int )sBackward.Peek()])
{
backward[( int )sBackward.Peek()] = 1;
sBackward.Pop();
}
sBackward.Push(i);
}
int res = 0;
for ( int i = 0; i < n; i++)
{
res += forward[i] + backward[i];
}
return res;
}
public static void Main()
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
Console.WriteLine(countPairs(arr, n));
}
}
|
Javascript
<script>
function countPairs(arr, n)
{
var forward = Array(n).fill(0);
var sForward = [];
for ( var i = 0; i < n; i++) {
while (sForward.length!=0
&& arr[i] > arr[sForward[sForward.length-1]]) {
forward[sForward[sForward.length-1]] = 1;
sForward.pop();
}
sForward.push(i);
}
var backward = Array(n).fill(0);
var sBackward = [];
for ( var i = n - 1; i >= 0; i--) {
while (sBackward.length != 0
&& arr[i] > arr[sBackward[sBackward.length-1]]) {
backward[sBackward[sBackward.length-1]] = 1;
sBackward.pop();
}
sBackward.push(i);
}
var res = 0;
for ( var i = 0; i < n; i++) {
res += forward[i] + backward[i];
}
return res;
}
var arr = [1, 2, 3, 4, 5];
var n = arr.length;
document.write( countPairs(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)