Tuesday, August 30, 2016

Maximum pair wise product using O(n)


Algorithm- MAXIMUM PAIRWISE PRODUCT

Time Complexity -O(n)


import java.util.Scanner;
//http://stackoverflow.com/questions/7961788/math-random-explained

public class MaxPairwiseProductFast {
     public static void main(String[] args) {
           Scanner scanner= new Scanner(System.in);
           int n=scanner.nextInt();
           long[] array = new long[n];
           for(int i=0;i<n;i++)
                array[i]=scanner.nextInt();
           long result= MaxPairWiseProduct(array);
           System.out.println(result);
     }   
     /*   12 51 17 82 13 97
     a)find index 1 with highest value - Iterate and find max value
     b)find index 2 with value smaller than highest value
     */  
     static long MaxPairWiseProduct(long[] array){
           int n=array.length;
           int index1=-1, index2=-1;
           for(int i=0;i<n;i++)
                if((index1==-1)|| (array[i]>array[index1]))
                index1=i;
           for(int j=0;j<n;j++)
                if((j != index1) &&((index2==-1)||                         (array[j]>array[index2])))
                index2=j;
           return (long)(array[index1]* array[index2]);
           }
     }

No comments:

Post a Comment