Find pair with greatest product in array | C ++ program to find the largest product number ; Function to find greatest number ; Store occurrences of all elements in hash array ; Sort the array and traverse all elements from end . ; For every element , check if there is another element which divides it . ; Check if the result value exists in array or not if yes the return arr [ i ] ; To handle the case like arr [ i ] = 4 and arr [ j ] = 2 ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findGreatest ( int arr [ ] , int n ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; sort ( arr , arr + n ) ; for ( int i = n - 1 ; i > 1 ; i -- ) { for ( int j = 0 ; j < i && arr [ j ] <= sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % arr [ j ] == 0 ) { int result = arr [ i ] / arr [ j ] ; if ( result != arr [ j ] && m [ result ] > 0 ) return arr [ i ] ; else if ( result == arr [ j ] && m [ result ] > 1 ) return arr [ i ] ; } } } return -1 ; } int main ( ) { int arr [ ] = { 17 , 2 , 1 , 15 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findGreatest ( arr , n ) ; return 0 ; }