Find largest product of two elements in an array using Java

Introduction

In this example we will see how to find largest product of two elements in an array using Java language. In other hand you can also find those two elements for which the largest product is computed among the elements of an array. The elements are assumed to be integer in an array. The element may be 0 or negative integer.

We will write a Java program to find out the largest product of two elements in an array and without sorting the array elements.

Prerequisites

Java

Find the Largest Product

Now we will write the below Java code to find out the desired result.

We first initialize two variable with the first and second elements respectively for performing product. Therefore we must have minimum two elements in the array to find the largest product of two elements.

Next we iterate through nested loops and compare the product

public static int largestProductInArrayWithoutSort(int[] arr) {
	int len = arr.length;

	if (len < 2) {
		throw new RuntimeException("Insufficient elements in array");
	}

	int a = arr[0], b = arr[1];

	int p = 1;

	for (int i = 0; i < len; i++) {
		for (int j = i + 1; j < len; j++) {
			if (arr[i] * arr[j] > a * b) {
				a = arr[i];
				b = arr[j];
				p = a * b;
			}
		}
	}

	return p;
}

Testing the Program

We can create a main method and test our program:

public static void main(String[] args) {
	int arr[] = { 1, 4, 3, 6, 7, 0 };

	System.out.println(largestProductInArrayWithoutSort(arr));
}

Running the above code will give you the following output:

42

That’s all.

Download Source Code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *