w3resource

Java Array Exercises: Find maximum product of two integers in a given array of integers

Java Array: Exercise-59 with Solution

Write a Java program to find maximum product of two integers in a given array of integers.

Example:
Input :
nums = { 2, 3, 5, 7, -7, 5, 8, -5 }
Output:
Pair is (7, 8), Maximum Product: 56

Sample Solution:

Java Code:

import java.util.*;
class solution
{
	public static void find_max_product(int[] nums)
	{
		int max_pair_product = Integer.MIN_VALUE;
		int max_i = -1, max_j = -1;

		for (int i = 0; i < nums.length - 1; i++)
		{
			for (int j = i + 1; j < nums.length; j++)
			{
				if (max_pair_product < nums[i] * nums[j])
				{
					max_pair_product = nums[i] * nums[j];
					max_i = i;
					max_j = j;
				}
			}
		}

		System.out.print("Pair is (" + nums[max_i] + ", " + nums[max_j] + "), Maximum Product: " + (nums[max_i]*nums[max_j]));
	}

	public static void main (String[] args)
	{
		int[] nums = { 2, 3, 5, 7, -7, 5, 8, -5 };
		System.out.println("\nOriginal array: "+Arrays.toString(nums));
		find_max_product(nums);
	}
}

Sample Output:

Original array: [2, 3, 5, 7, -7, 5, 8, -5]
Pair is (7, 8), Maximum Product: 56 

Flowchart:

Flowchart: Find maximum product of two integers in a given array of integers

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to merge elements of A with B by maintaining the sorted order.
Next: Write a Java program to shuffle a given array of integers.

What is the difficulty level of this exercise?



Java: Tips of the Day

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

Ref: https://bit.ly/3vRuIPY