Maximum Product of Two Elements in an Array

Updated on 10 June, 2025
Maximum Product of Two Elements in an Array header image

Problem Statement

In the given problem, you are provided with an array of integers named nums. Your task is to identify two distinct indices i and j from this array such that the expression (nums[i]-1)*(nums[j]-1) attains its maximum possible value. The result you should return is this maximum value. This problem leverages basic array indexing and mathematical operations to find the optimum pair of numbers which when modified slightly (decremented by 1), their product is maximized.

Examples

Example 1

Input:

nums = [3,4,5,2]

Output:

12

Explanation:

If you choose the indices i=1 and j=2 (indexed from 0), you 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), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3

Input:

nums = [3,7]

Output:

12

Constraints

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3

Approach and Intuition

The primary goal here is to maximize the product of the values (nums[i]-1) and (nums[j]-1). This can theoretically be achieved by picking the two largest numbers in the array nums because once decremented by 1, their product will most likely be larger than that formed with smaller numbers. Here's a straightforward way to solve the problem:

  1. Identify the two largest numbers in the array. Since sorting the array can simplify identification, we might start with that approach.

    • Sort the array in descending order.
    • Identify the two largest elements, which will be located at the beginning of the sorted array.
  2. Calculate the product (nums[0]-1)*(nums[1]-1).

    • This ensures that you are maximizing the product since nums[0] and nums[1] are the largest elements in the sorted array.

This approach is efficient given the constraints and directly utilizes array indexing and sorting (where sorting dominates the computational complexity). The maximum possible size for the array is 500, making a sorting operation feasible, and since any sorting algorithm typically performs well within this range, the overall algorithm remains efficient.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int maximumProduct(vector<int>& numbers) {
        int largest = 0;
        int secondLargest = 0;
        for (int value : numbers) {
            if (value > largest) {
                secondLargest = largest;
                largest = value;
            } else {
                secondLargest = max(secondLargest, value);
            }
        }
        
        return (largest - 1) * (secondLargest - 1);
    }
};

This C++ solution focuses on finding the maximum product of two different elements in an array after each element has been decreased by one. The function maximumProduct receives a vector of integers and processes to find the two largest distinct values in the array.

  • Start by initializing two integer variables, largest and secondLargest, both set to zero.
  • Iterate through the numbers vector using a range-based for loop.
  • During each iteration, compare the current value with largest. If it's greater:
    • Update secondLargest to the value of largest.
    • Set largest to the current value.
  • If the current value isn't larger than largest, update secondLargest to be the maximum of the current secondLargest and the current value.
  • Finally, calculate and return the product (largest - 1) * (secondLargest - 1).

This solution efficiently identifies the two largest unique values in a single traversal of the array, leading to an optimal time complexity of O(n), where n is the number of elements in the input vector.

java
class Solution {
    public int maximumProduct(int[] values) {
        int max1 = 0;
        int max2 = 0;
        for (int value : values) {
            if (value > max1) {
                max2 = max1;
                max1 = value;
            } else {
                max2 = Math.max(max2, value);
            }
        }
        
        return (max1 - 1) * (max2 - 1);
    }
}

The code provided is a Java solution intended to find the maximum product of two elements minus one for each, from an input array. The function, maximumProduct, takes an integer array values as input. Here's a breakdown of how the solution is calculated:

  • Initialize two integers, max1 and max2, both set to 0. These variables keep track of the largest and second-largest values in the array.
  • Iterate through each element in the values array:
    • For each element, check if it is greater than max1.
      • If true, the current max1 becomes max2, and max1 is updated to the current value.
      • If false, update max2 to be the maximum between the current max2 and the value.
  • Finally, subtract one from both max1 and max2, multiply them together, and return the result.

The procedure employs a single pass through the array, keeping the solution efficient with a time complexity of O(n), where n is the number of elements in the array. This method ensures that max1 always holds the highest value found, and max2 the second highest, which are required to calculate the desired product. This efficient method not only finds these values without sorting but also avoids using extra space, making it space-efficient with O(1) space complexity.

python
class Solution:
    def calculateMaxProduct(self, numbers: List[int]) -> int:
        max1 = 0
        max2 = 0
        for n in numbers:
            if n > max1:
                max2 = max1
                max1 = n
            elif n > max2:
                max2 = n
        
        return (max1 - 1) * (max2 - 1)

The provided code defines a Python function that determines the maximum product of two numbers from a list after decrementing each by one. The function, calculateMaxProduct, iterates through the list to identify the largest (max1) and second largest (max2) numbers. Using conditional logic during the iteration, it updates max1 and max2 appropriately. Once the maximum two numbers are identified, the function computes their product after subtracting one from each, and then returns the result.

Here's a concise overview on how the solution functions:

  • Initialize two variables, max1 and max2, to zero to store the maximum and the second maximum numbers from the list.
  • Loop through each number n in the provided list:
    • Update max1 and max2 accordingly if n is greater than max1 or n is greater than max2.
  • After completion of the loop, return the product (max1 - 1) * (max2 - 1).

This approach efficiently determines the required maximum product by only scanning the list once, hence operates in O(n) time complexity, where n is the number of elements in the list.

Comments

No comments yet.