1. Introduction
Given an array of integers, we are tasked to find the maximum product that can be achieved using any two numbers from the array. This problem tests the ability to evaluate the product potential of the array’s numbers, considering both positive and negative values.
2. Program Steps
1. Initialize two variables, maxProduct and n, where maxProduct will store the maximum product, and n will store the size of the array.
2. If the array size is less than 2, return an error since we cannot form a product with less than two numbers.
3. Traverse through the array in a nested loop to evaluate products of all combinations of numbers:
a. For every pair (arr[i], arr[j]) where i is not equal to j, calculate their product.
b. Update maxProduct if the current product is greater than maxProduct.
4. Return maxProduct as the result.
3. Code Program
public class MaxProduct {
public static int maxProduct(int[] arr) {
int n = arr.length;
// If the array has less than 2 elements
if (n < 2) {
System.out.println("No pairs exist");
return Integer.MIN_VALUE;
}
int maxProduct = Integer.MIN_VALUE;
// Traverse through every possible pair in the array
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
maxProduct = Math.max(maxProduct, arr[i] * arr[j]);
}
}
return maxProduct;
}
public static void main(String[] args) {
int[] arr = { -10, -3, 5, 6, 2 };
System.out.println("Maximum Product is: " + maxProduct(arr));
}
}
Output:
Maximum Product is: 30
4. Step By Step Explanation
1. The maxProduct function calculates the maximum product from pairs of numbers in the array.
2. Two nested loops run to get all pairs of numbers in the array. The product of each pair is calculated.
3. We use the Math.max method to update the maxProduct if the current product of a pair is higher than the previous maxProduct.
4. The test array is {-10, -3, 5, 6, 2}. While one might initially assume the product of the two largest numbers (6 and 5) to be the maximum, it's the product of -10 and -3 (which equals 30) that is the largest.