Given an array arr[] of N integers, where N > 2, the task is to find the second largest product pair from the given array.
Examples:
Input: arr[] = {10, 20, 12, 40, 50}
Output: 20 50
Explanation:
A pair of array elements = [(10, 20), (10, 12), (10, 40), (10, 50), (20, 12), (20, 40), (20, 50), (12, 40), (12, 50), (40, 50)]
If do product of each pair will get the largest pair as (40, 50) and second largest pair (20, 50)Input: arr[] = {5, 2, 67, 45, 160, 78}
Output: 67 160
Naive Approach: The naive approach is to generate all possible pairs from the given array and insert the product with the pair into the set of pairs. After inserting all the pair products in the set print the second last product of the set. Below are the steps:
- Make a set of pairs and their products by the given array.
- Insert all the pairs in vector of pairs.
- If vector size is 1 then print this pair otherwise print the pair at (total vector size – 2)th position of vector.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find second largest // product of pairs void secondLargerstPair( int arr[], int N) { Â
    // If size of array is less than 3     // then second largest product pair     // does not exits.     if (N < 3)         return ; Â
    // Declaring set of pairs which     // contains possible pairs of array     // and their products     set<pair< int , pair< int , int > > > s; Â
    // Declaring vector of pairs     vector<pair< int , int > > v; Â
    for ( int i = 0; i < N; ++i) { Â
        for ( int j = i + 1; j < N; ++j) { Â
            // Inserting a set             s.insert(make_pair(arr[i] * arr[j],                                make_pair(arr[i],                                          arr[j])));         }     } Â
    // Traverse set of pairs     for ( auto i : s) { Â
        // Inserting values in vector         // of pairs         v.push_back(             make_pair((i.second).first,                       (i.second).second));     } Â
    int vsize = v.size(); Â
    // Printing the result     cout << v[vsize - 2].first << " "          << v[vsize - 2].second << endl; } Â
// Driver Code int main() {     // Given Array     int arr[] = { 5, 2, 67, 45, 160, 78 }; Â
    // Size of Array     int N = sizeof (arr) / sizeof (arr[0]); Â
    // Function Call     secondLargerstPair(arr, N);     return 0; } |
Java
/*package whatever //do not write package name here */ import java.util.*; public class GFG { Â
  static class Tuple<K,V>{ Â
    K key;     V val; Â
    Tuple(K k, V v){       key = k;       val = v;     } Â
  } Â
  // Function to find second largest   // product of pairs   static void secondLargerstPair( int [] arr, int N)   { Â
    // If size of array is less than 3     // then second largest product pair     // does not exits.     if (N < 3 )       return ; Â
    // Declaring set of pairs which     // contains possible pairs of array     // and their products     TreeSet<Tuple<Integer, Tuple<Integer, Integer>>> s = new TreeSet<>((t1,t2)->{ Â
      int a1 = t1.key, a2 = t1.val.key, a3 = t1.val.val;       int b1 = t2.key, b2 = t2.val.key, b3 = t2.val.val; Â
      if (a1 < b1)         return - 1 ;       if (a1 > b1)         return 1 ;       if (a2 < b2)         return - 1 ;       if (a2 > b2)         return 1 ;       if (a3 < b3)         return - 1 ;       if (a3 > b3)         return 1 ;       return 0 ; Â
    }); Â
    // Declaring vector of pairs     List<Tuple<Integer, Integer> > v = new ArrayList<>(); Â
    for ( int i = 0 ; i < N; ++i) { Â
      for ( int j = i + 1 ; j < N; ++j) { Â
        // Inserting a set         s.add( new Tuple(arr[i] * arr[j], new Tuple(arr[i],arr[j])));       }     } Â
    // Traverse set of pairs     for (var i : s){ Â
      // Inserting values in vector       // of pairs       v.add( new Tuple((i.val).key,(i.val).val));     } Â
    Collections.sort(v,(a,b)->a.key - b.key); Â
    int vsize = v.size(); Â
    // Printing the result     System.out.println(v.get(vsize - 2 ).key + " " + v.get(vsize - 2 ).val);   } Â
  // Driver Code   public static void main(String[] args)   { Â
    // Given Array     int [] arr = { 5 , 2 , 67 , 45 , 160 , 78 }; Â
    // Size of Array     int N = arr.length; Â
    // Function Call     secondLargerstPair(arr, N);   } } Â
// This code is contributed by aadityaburujwale. |
Python3
#Â Python3 program for the above approach Â
# Function to find second largest # product of pairs def secondLargerstPair(arr, N): Â
    # If size of array is less than 3     # then second largest product pair     # does not exits.     if (N < 3 ):         return ; Â
    # Declaring set of pairs which     # contains possible pairs of array     # and their products     s = set () Â
    # Declaring vector of pairs     v = []; Â
    for i in range (N):         for j in range (i + 1 , N):                          # Inserting a set             s.add((arr[i] * arr[j], (arr[i], arr[j])))          # Traverse set of pairs     for i in sorted (s): Â
        # Inserting values in vector         # of pairs         v.append((i[ 1 ][ 0 ], i[ 1 ][ 1 ]));          vsize = len (v) Â
    # Printing the result     print (v[vsize - 2 ][ 0 ], v[vsize - 2 ][ 1 ]); Â
# Driver Code Â
# Given Array arr = Â [ 5 , 2 , 67 , 45 , 160 , 78 ]; Â
# Size of Array N = len (arr) Â
# Function Call secondLargerstPair(arr, N); Â
# This code is contributed by phasing17 |
C#
// C# program for the above approach using System; using System.Collections.Generic; Â
class GFG {   // Function to find second largest   // product of pairs   static void secondLargerstPair( int [] arr, int N)   { Â
    // If size of array is less than 3     // then second largest product pair     // does not exits.     if (N < 3)       return ; Â
    // Declaring set of pairs which     // contains possible pairs of array     // and their products     HashSet<Tuple< int , Tuple< int , int > > > s = new HashSet<Tuple< int , Tuple< int , int > > >(); Â
    // Declaring vector of pairs     List<Tuple< int , int > > v = new List<Tuple< int , int > >(); Â
    for ( int i = 0; i < N; ++i) { Â
      for ( int j = i + 1; j < N; ++j) { Â
        // Inserting a set         s.Add(Tuple.Create(arr[i] * arr[j], Tuple.Create(arr[i],                                                          arr[j])));       }     } Â
    // Traverse set of pairs     foreach ( var i in s) { Â
      // Inserting values in vector       // of pairs       v.Add(         Tuple.Create((i.Item2).Item1,                      (i.Item2).Item2));     } Â
    v.Sort(); Â
    int vsize = v.Count; Â
    // Printing the result     Console.WriteLine(v[vsize - 2].Item1 + " "                       + v[vsize - 2].Item2);   } Â
  // Driver Code   public static void Main( string [] args)   {          // Given Array     int [] arr = { 5, 2, 67, 45, 160, 78 }; Â
    // Size of Array     int N = arr.Length; Â
    // Function Call     secondLargerstPair(arr, N);   } } Â
// This code is contributed by phasing17 |
Javascript
//Â JS program for the above approach Â
// Function to find second largest // product of pairs function secondLargerstPair(arr, N) { Â
    // If size of array is less than 3     // then second largest product pair     // does not exits.     if (N < 3)         return ; Â
    // Declaring set of pairs which     // contains possible pairs of array     // and their products     let s = new Set() Â
    // Declaring vector of pairs     let v = []; Â
    for ( var i = 0; i < N; i++)         for ( var j = i + 1; j < N; j++)                          // Inserting a set             s.add([arr[i] * arr[j], arr[i], arr[j]].join( '#' ))          // Traverse set of pairs     s = Array.from(s)     s.sort( function (a, b)     {         a = a.split( '#' )         b = b.split( '#' )         let a1 = parseInt(a[0]), a2 = parseInt(a[1]), a3 = parseInt(a[2])         let b1 = parseInt(b[0]), b2 = parseInt(b[1]), b3 = parseInt(b[2])                  if (a1 < b1)             return -1         if (a1 > b1)             return 1         if (a2 < b2)             return -1         if (a2 > b2)             return 1         if (a3 < b3)             return -1         if (a3 > b3)             return 1         return 0 Â
    })     for (let i of s)     {         i = i.split( '#' )                  // Inserting values in vector         // of pairs         v.push([i[1], i[2]])     }     let vsize = v.length Â
    // Printing the result     console.log(v[vsize - 2].join( ' ' )) } // Driver Code Â
// Given Array let arr =Â [5, 2, 67, 45, 160, 78]; Â
// Size of Array let N = arr.length Â
// Function Call secondLargerstPair(arr, N); Â
// This code is contributed by phasing17 |
67 160
Time Complexity: O(N2)Â
Auxiliary Space: O(N), since n extra space has been taken.
Better Solution: A better solution is to traverse all the pairs of the array and while traversing store the largest and second-largest product pairs. After traversal print the pairs with second-largest pairs stored.Â
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find second largest // product pair in arr[0..n-1] void maxProduct( int arr[], int N) {     // No pair exits     if (N < 3) {         return ;     } Â
    // Initialize max product pair     int a = arr[0], b = arr[1];     int c = 0, d = 0; Â
    // Traverse through every possible pair     // and keep track of largest product     for ( int i = 0; i < N; i++)         for ( int j = i + 1; j < N; j++) { Â
            // If pair is largest             if (arr[i] * arr[j] > a * b) { Â
                // Second largest                 c = a, d = b;                 a = arr[i], b = arr[j];             } Â
            // If pair does not largest but             // larger than second largest             if (arr[i] * arr[j] < a * b                 && arr[i] * arr[j] > c * d)                 c = arr[i], d = arr[j];         } Â
    // Print the pairs     cout << c << " " << d; } Â
// Driver Code int main() {     // Given array     int arr[] = { 5, 2, 67, 45, 160, 78 };     int N = sizeof (arr) / sizeof (arr[0]); Â
    // Function Call     maxProduct(arr, N);     return 0; } |
Java
// Java program for the above approach class GFG{    // Function to find second largest // product pair in arr[0..n-1] static void maxProduct( int arr[], int N) {     // No pair exits     if (N < 3 )     {         return ;     }       // Initialize max product pair     int a = arr[ 0 ], b = arr[ 1 ];     int c = 0 , d = 0 ;       // Traverse through every possible pair     // and keep track of largest product     for ( int i = 0 ; i < N; i++)         for ( int j = i + 1 ; j < N- 1 ; j++)         {               // If pair is largest             if (arr[i] * arr[j] > a * b)             {                   // Second largest                 c = a;                 d = b;                 a = arr[i];                 b = arr[j];             }               // If pair does not largest but             // larger than second largest             if (arr[i] * arr[j] < a * b &&                 arr[i] * arr[j] > c * d)                 c = arr[i];                 d = arr[j];         }       // Print the pairs     System.out.println(c + " " + d); }   // Driver Code public static void main(String[] args) {     // Given array     int arr[] = { 5 , 2 , 67 , 45 , 160 , 78 };     int N = arr.length;       // Function Call     maxProduct(arr, N); } } Â
// This code is contributed by Ritik Bansal |
Python3
# Python3 program for the above approach Â
# Function to find second largest # product pair in arr[0..n-1] def maxProduct(arr, N):          # No pair exits     if (N < 3 ):         return ;          # Initialize max product pair     a = arr[ 0 ]; b = arr[ 1 ];     c = 0 ; d = 0 ; Â
    # Traverse through every possible pair     # and keep track of largest product     for i in range ( 0 , N, 1 ):         for j in range (i + 1 , N - 1 , 1 ): Â
            # If pair is largest             if (arr[i] * arr[j] > a * b): Â
                # Second largest                 c = a;                 d = b;                 a = arr[i];                 b = arr[j];                          # If pair does not largest but             # larger than second largest             if (arr[i] * arr[j] < a * b and                 arr[i] * arr[j] > c * d):                 c = arr[i];                              d = arr[j];              # Print the pairs     print (c, " " , d); Â
# Driver Code if __name__ = = '__main__' :          # Given array     arr = [ 5 , 2 , 67 , 45 , 160 , 78 ];     N = len (arr); Â
    # Function call     maxProduct(arr, N); Â
# This code is contributed by Amit Katiyar |
C#
// C# program for the above approach using System; Â
class GFG{ Â
// Function to find second largest // product pair in arr[0..n-1] static void maxProduct( int []arr, int N) {          // No pair exits     if (N < 3)     {         return ;     } Â
    // Initialize max product pair     int a = arr[0], b = arr[1];     int c = 0, d = 0; Â
    // Traverse through every possible pair     // and keep track of largest product     for ( int i = 0; i < N; i++)         for ( int j = i + 1; j < N - 1; j++)         {                          // If pair is largest             if (arr[i] * arr[j] > a * b)             { Â
                // Second largest                 c = a;                 d = b;                 a = arr[i];                 b = arr[j];             } Â
            // If pair does not largest but             // larger than second largest             if (arr[i] * arr[j] < a * b &&                 arr[i] * arr[j] > c * d)                 c = arr[i];                 d = arr[j];         } Â
    // Print the pairs     Console.WriteLine(c + " " + d); } Â
// Driver Code public static void Main(String[] args) {          // Given array     int []arr = { 5, 2, 67, 45, 160, 78 };     int N = arr.Length; Â
    // Function call     maxProduct(arr, N); } } Â
// This code is contributed by 29AjayKumar |
Javascript
<script> Â
// JavaScript program for the above approach Â
// Function to find second largest // product pair in arr[0..n-1] function maxProduct(arr, N) {     // No pair exits     if (N < 3) {         return ;     } Â
    // Initialize max product pair     let a = arr[0], b = arr[1];     let c = 0, d = 0; Â
    // Traverse through every possible pair     // and keep track of largest product     for (let i = 0; i < N; i++)         for (let j = i + 1; j < N; j++) { Â
            // If pair is largest             if (arr[i] * arr[j] > a * b) { Â
                // Second largest                 c = a, d = b;                 a = arr[i], b = arr[j];             } Â
            // If pair does not largest but             // larger than second largest             if (arr[i] * arr[j] < a * b                 && arr[i] * arr[j] > c * d)                 c = arr[i], d = arr[j];         } Â
    // Print the pairs     document.write(c + " " + d); } Â
// Driver Code     // Given array     let arr = [ 5, 2, 67, 45, 160, 78 ];     let N = arr.length; Â
    // Function Call     maxProduct(arr, N); Â
// This code is contributed by Surbhi Tyagi. Â
</script> |
67 160
Time Complexity: O(N2)Â
Auxiliary Space: O(N)Â
Efficient Approach:
- Sort the array.
- Find first and third smallest elements for handling negative numbers.
- Find the first and third largest elements for handling positive numbers.
- Compare the product of the smallest pair and largest pair.
- Return the largest one of them.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find second largest // product pair in arr[0..n-1] void maxProduct( int arr[], int N) {     // No pair exits     if (N < 3) {         return ;     } Â
    // Sort the array     sort(arr, arr + N); Â
    // Initialize smallest element     // of the array     int smallest1 = arr[0];     int smallest3 = arr[2]; Â
    // Initialize largest element     // of the array     int largest1 = arr[N - 1];     int largest3 = arr[N - 3]; Â
    // Print second largest product pair     if (smallest1 * smallest3         >= largest1 * largest3) {         cout << smallest1 << " " << smallest3;     }     else {         cout << largest1 << " " << largest3;     } } Â
// Driver Code int main() {     // Given array     int arr[] = { 5, 2, 67, 45, 160, 78 }; Â
    int N = sizeof (arr) / sizeof (arr[0]); Â
    // Function Call     maxProduct(arr, N);     return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG{ Â
// Function to find second largest // product pair in arr[0..n-1] static void maxProduct( int arr[], int N) {     // No pair exits     if (N < 3 )     {         return ;     } Â
    // Sort the array     Arrays.sort(arr); Â
    // Initialize smallest element     // of the array     int smallest1 = arr[ 0 ];     int smallest3 = arr[ 2 ]; Â
    // Initialize largest element     // of the array     int largest1 = arr[N - 1 ];     int largest3 = arr[N - 3 ]; Â
    // Print second largest product pair     if (smallest1 * smallest3 >=         largest1 * largest3)     {         System.out.print(smallest1 + " " +                          smallest3);     }     else     {         System.out.print(largest1 + " " +                          largest3);     } } Â
// Driver Code public static void main(String[] args) {     // Given array     int arr[] = { 5 , 2 , 67 , 45 , 160 , 78 }; Â
    int N = arr.length; Â
    // Function Call     maxProduct(arr, N); } } Â
// This code is contributed by gauravrajput1 |
Python3
# Python3 program for the above approach Â
# Function to find second largest # product pair in arr[0..n-1] def maxProduct(arr, N):        # No pair exits     if (N < 3 ):         return ; Â
    # Sort the array     arr.sort(); Â
    # Initialize smallest element     # of the array     smallest1 = arr[ 0 ];     smallest3 = arr[ 2 ]; Â
    # Initialize largest element     # of the array     largest1 = arr[N - 1 ];     largest3 = arr[N - 3 ]; Â
    # Print second largest product pair     if (smallest1 *         smallest3 > = largest1 *                      largest3):         print (smallest1 , " " , smallest3);     else :         print (largest1 , " " , largest3); Â
# Driver Code if __name__ = = '__main__' :        # Given array     arr = [ 5 , 2 , 67 , 45 , 160 , 78 ]; Â
    N = len (arr); Â
    # Function Call     maxProduct(arr, N); Â
# This code is contributed by sapnasingh4991 |
C#
// C# program for the above approach using System; class GFG{ Â
// Function to find second largest // product pair in arr[0..n-1] static void maxProduct( int []arr, int N) {     // No pair exits     if (N < 3)     {         return ;     } Â
    // Sort the array     Array.Sort(arr); Â
    // Initialize smallest element     // of the array     int smallest1 = arr[0];     int smallest3 = arr[2]; Â
    // Initialize largest element     // of the array     int largest1 = arr[N - 1];     int largest3 = arr[N - 3]; Â
    // Print second largest product pair     if (smallest1 * smallest3 >=         largest1 * largest3)     {         Console.Write(smallest1 + " " +                       smallest3);     }     else     {         Console.Write(largest1 + " " +                       largest3);     } } Â
// Driver Code public static void Main(String[] args) {     // Given array     int []arr = { 5, 2, 67, 45, 160, 78 }; Â
    int N = arr.Length; Â
    // Function Call     maxProduct(arr, N); } } Â
// This code is contributed by Rohit_ranjan |
Javascript
<script> // JavaScript program for the above approach Â
// Function to find second largest // product pair in arr[0..n-1] function maxProduct(arr, N) {     // No pair exits     if (N < 3)     {         return ;     }       // Sort the array     arr.sort((a, b) => a - b)       // Initialize smallest element     // of the array     let smallest1 = arr[0];     let smallest3 = arr[2];       // Initialize largest element     // of the array     let largest1 = arr[N - 1];     let largest3 = arr[N - 3];       // Print second largest product pair     if (smallest1 * smallest3 >=         largest1 * largest3)     {         document.write(smallest1 + " " +                          smallest3);     }     else     {         document.write(largest1 + " " +                          largest3);     } }      // Driver Code             // Given array     let arr = [ 5, 2, 67, 45, 160, 78 ];       let N = arr.length;       // Function Call     maxProduct(arr, N);               </script> |
160 67
Time Complexity: O(N*log N)Â
Auxiliary Space: O(1), since no extra space has been taken.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!