Java program to Find Maximum Product of Two Elements in Array

Problem Statement:

  • Given the array of integers.
  • Choose two different indices i and j of that array.
  • Find out product of two elements in array such that (nums[i]-1)*(nums[j]-1) is maximum.
  • We have discussed similar problem to find out second largest element in an array.

Example to Find Maximum Product of Two Elements

Example 1:
 
Input: nums = [3,4,5,2]
Output: 12
 
Explanation: If we choose the indices i=1 and j=2 (0 bound array),
we will get the maximum value,
that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
 
Example 2:
 
Input: nums = [1,5,4,5]
Output: 16
 
Explanation: Choosing the indices i=1 and j=3 (indexed from 0),
 
we will get the maximum value of (5-1)*(5-1) = 16.
 
 
Example 3:
 
Input: nums = [3,7]
Output: 12

Algorithm to Calculate Maximum Product of Two Elements:

  • Declare max & secondMax element.
  • Iterate through array.
    • Find maximum & second maximum element
  • Calculate product of maximum & second maximum element

Program to Maximum Product of Two Elements in an Array

package org.learn;
 
public class MaxProductTwoElement {
 
    public static int maxProduct(int[] nums) {
 
        int max = Integer.MIN_VALUE;
        int secondMax = max;
 
        for(int number : nums) {
            if(max < number) {
                secondMax = max;
                max = number;
            } else if(secondMax < number) {
                secondMax = number;
            }
        }
        return (max-1) * (secondMax-1);
    }
 
    public static void main(String[] args) {
 
        int arr[] = {3,4,5,2};
        System.out.println("Output :" + maxProduct(arr));
 
        int inputArr[] = {1,5,4,5};
        System.out.println("Output :" + maxProduct(inputArr));
 
        int arrVal[] = {3,7};
        System.out.println("Output :" + maxProduct(arrVal));
    }
}

Output: Maximum Product of Two Elements in an Array

Output :12
Output :16
Output :12