﻿ Java exercises: Find maximum product of two integers in a given array of integers - 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: Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

﻿

## Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

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