Skip to content
Related Articles

Related Articles

Find the number of unique pairs satisfying given conditions
  • Last Updated : 03 Feb, 2020

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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the count
// of the required pairs
int countPairs(int arr[], int n)
{
  
    // Calculating the valid pairs
    // in forward direction
    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);
    }
  
    // Calculating the valid pairs
    // in backward direction
    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);
    }
  
    // Calculating the total number of pairs
    int res = 0;
    for (int i = 0; i < n; i++) {
        res += forward[i] + backward[i];
    }
    return res;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << countPairs(arr, n);
  
    return 0;
}

Java




// Java implementation of the approach
import java.util.*; 
  
class GFG
{
  
    // Function to return the count 
    // of the required pairs 
    static int countPairs(int arr[], int n) 
    
      
        // Calculating the valid pairs 
        // in forward direction 
        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); 
        
      
        // Calculating the valid pairs 
        // in backward direction 
        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); 
        
      
        // Calculating the total number of pairs 
        int res = 0
        for (int i = 0; i < n; i++)
        
            res += forward[i] + backward[i]; 
        
        return res; 
    
      
    // Driver code 
    public static void main (String[] args)
    
        int arr[] = { 1, 2, 3, 4, 5 }; 
        int n = arr.length; 
      
        System.out.println(countPairs(arr, n)); 
    }
}
  
// This code is contributed by AnkitRai01

Python3




# Python3 implementation of the approach 
  
# Function to return the count 
# of the required pairs 
def countPairs(arr, n) : 
  
    # Calculating the valid pairs 
    # in forward direction 
    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); 
  
    # Calculating the valid pairs 
    # in backward direction 
    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); 
  
    # Calculating the total number of pairs 
    res = 0
    for i in range(n) :
        res += forward[i] + backward[i]; 
  
    return res; 
  
# Driver code 
if __name__ == "__main__"
  
    arr = [ 1, 2, 3, 4, 5 ]; 
      
    n = len(arr); 
  
    print(countPairs(arr, n)); 
  
# This code is contributed by AnkitRai01

C#




// C# implementation of the approach 
using System;
using System.Collections; 
  
class GFG 
  
    // Function to return the count 
    // of the required pairs 
    static int countPairs(int []arr, int n) 
    
      
        // Calculating the valid pairs 
        // in forward direction 
        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); 
        
      
        // Calculating the valid pairs 
        // in backward direction 
        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); 
        
      
        // Calculating the total number of pairs 
        int res = 0; 
        for (int i = 0; i < n; i++) 
        
            res += forward[i] + backward[i]; 
        
        return res; 
    
      
    // Driver code 
    public static void Main() 
    
        int []arr = { 1, 2, 3, 4, 5 }; 
        int n = arr.Length; 
      
        Console.WriteLine(countPairs(arr, n)); 
    
  
// This code is contributed by AnkitRai01 
Output:
4

Time Complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
Recommended Articles
Page :