Let’s find out the maximum product of two biggest numbers in a given array. We will implement this in Java. Before that you need to understand how to find out biggest number in a given array, Please refer to the blog post below,
Example in Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.StringTokenizer; public class MaxPairwiseProduct { static BigInteger getMaxPairwiseProductFast(int[] numbers) { int n = numbers.length; //System.out.println("size is: "+n); int index1 = 0; int index2; for (int i = 1; i < n; i++) { if (numbers[i] > numbers[index1]) { index1 = i; } } //System.out.println("Highest number is: "+numbers[index1]); if (index1 == 0) { index2 = 1; } else { index2 = 0; } for (int i = 1; i < n; i++) { if (i != index1 && numbers[i] > numbers[index2]) index2 = i; } BigInteger x = new BigInteger(Integer.toString(numbers[index1])); BigInteger y = new BigInteger(Integer.toString(numbers[index2])); return x.multiply(y); } public static void main(String[] args) { FastScanner scanner = new FastScanner(System.in); int n = scanner.nextInt(); int[] numbers = new int[n]; for (int i = 0; i < n; i++) { numbers[i] = scanner.nextInt(); } System.out.println(getMaxPairwiseProductFast(numbers)); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } }
Result
4 4 3 9 1 Highest number is: 9 36
Please observe the condition below,
if (index1 == 0) { index2 = 1; } else { index2 = 0; }
We are making sure, that if index1=0
which means that the highest number is at first place (index=0) then index2=1
otherwise the initial value of index2
will get be equal to index1
and will remain.
Explanation
For Example, if we are not using this condition,
consider the data set, a[4 2 3]
Say we have not used the condition so On first loop index1
will be 0
On the second loop index2
will have initial value of 0
a[0] > a[index2] && 0 != 0 —> FALSE —> index2 remains 0 (i.e; value 4
)
a[1] > a[index2] && 1 != 0 —> FALSE —> index2 remains 0 (i.e; value 4
)
a[2] > a[index2] && 2 != 0 —> FALSE —> index2 remains 0 (i.e; value 4
)