Pair with greatest product in array

PROBLEM :
Given an array of n elements, the task is to find the greatest number such that it is product of two elements of given array. If no such element exists, print -1.

Input :  A[] = {10, 3, 5, 30, 35}
Output:  30
Explanation: 30 is the product of 10 and 3.

Input :  A[] = {2, 5, 7, 8}
Output:  -1
Explanation: Since, no such element exists.

Input :  A[] = {10, 2, 4, 30, 35}
Output:  -1

Input :  A[] = {10, 2, 2, 4, 30, 35}
Output:  4

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer n denoting size of the array. Then in the next line are n space separated values of the array.

Output:
For each test case in a new line print the required output.

Constraints:
1<=T<=100
1<=n<=100
1<=A[]<=100

Example:
Input:
2
4
2 5 7 8
6
10 2 2 4 30 35

Output:
-1
4

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<algorithm>
#define max 100
int greatest_product(int [],int ) ;
int main()
{
    int t,no,i ;
    int arr[max] ;
    cin>>t ;
    while(t--)
    {
        cin>>no ;
        for(i=0;i<no;i++)
            cin>>arr[i] ;
           
        cout<<greatest_product(arr,no)<<endl ;
    }
return 0;
}

int greatest_product(int arr[],int no)
{
    sort(arr,arr+no) ;
    int i,j,k ;
   
    for(k=no-1;k>=2;k--)
    {
        i=0 ;
        j=k ;
        while(i<j)
        {
            if(arr[i]*arr[j]>arr[k])
                j-- ;
            else if(arr[i]*arr[j]<arr[k])
                i++ ;
            else
                return arr[k] ;
        }
    }
    return -1 ;
}

---------------------------------------------------------------------------------

Comments