Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe