Maximum Product of Two Elements in an Array

Last Updated : 1 May, 2026

Given an array arr[] of non-negative integers, find the maximum product of any two elements present in the array.

Examples:  

Input: arr[] = {1, 4, 3, 6, 7, 0}
Output: 42
Explanation: The maximum product is obtained by multiplying 6 and 7.

Input: arr[] = {0, 2, 5, 3}
Output: 15
Explanation: The maximum product is obtained by multiplying 5 and 3.

Try It Yourself
redirect icon

[Naive Approach] Using Nested Loop - O(n²) Time and O(1) Space

The simplest way to solve this problem is to check the product of every possible pair in the array and keep track of the maximum product.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find maximum product of any two elements
int maxProduct(vector<int> &arr)
{
    int n = arr.size();

    // If there are less than 2 elements, no pair exists
    if (n < 2)
        return -1;

    // Initialize maximum product with smallest possible value
    int maxProd = INT_MIN;

    // Traverse all possible pairs
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {

            // Calculate product of current pair
            int product = arr[i] * arr[j];

            // Update maximum product if needed
            maxProd = max(maxProd, product);
        }
    }

    return maxProd;
}

int main()
{
    vector<int> arr = {1, 4, 3, 6, 7, 0};
    cout << maxProduct(arr);
    return 0;
}
Java
class GFG {

    // Function to find maximum product of any two elements
    static int maxProduct(int[] arr) {
        int n = arr.length;

        // If there are less than 2 elements, no pair exists
        if (n < 2)
            return -1;

        // Initialize maximum product with smallest possible value
        int maxProd = Integer.MIN_VALUE;

        // Traverse all possible pairs
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Calculate product of current pair
                int product = arr[i] * arr[j];

                // Update maximum product if needed
                maxProd = Math.max(maxProd, product);
            }
        }

        return maxProd;
    }

    public static void main(String[] args) {
        int[] arr = {1, 4, 3, 6, 7, 0};
        System.out.println(maxProduct(arr));
    }
}
Python
# Function to find maximum product of any two elements
def maxProduct(arr):
    n = len(arr)

    # If there are less than 2 elements, no pair exists
    if n < 2:
        return -1

    # Initialize maximum product with smallest possible value
    maxProd = float('-inf')

    # Traverse all possible pairs
    for i in range(n):
        for j in range(i + 1, n):

            # Calculate product of current pair
            product = arr[i] * arr[j]

            # Update maximum product if needed
            maxProd = max(maxProd, product)

    return maxProd


if __name__ == "__main__":
    arr = [1, 4, 3, 6, 7, 0]
    print(maxProduct(arr))
C#
using System;

class GFG {

    // Function to find maximum product of any two elements
    static int maxProduct(int[] arr) {
        int n = arr.Length;

        // If there are less than 2 elements, no pair exists
        if (n < 2)
            return -1;

        // Initialize maximum product with smallest possible value
        int maxProd = int.MinValue;

        // Traverse all possible pairs
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Calculate product of current pair
                int product = arr[i] * arr[j];

                // Update maximum product if needed
                maxProd = Math.Max(maxProd, product);
            }
        }

        return maxProd;
    }

    static void Main() {
        int[] arr = {1, 4, 3, 6, 7, 0};
        Console.WriteLine(maxProduct(arr));
    }
}
JavaScript
// Function to find maximum product of any two elements
function maxProduct(arr) {
    let n = arr.length;

    // If there are less than 2 elements, no pair exists
    if (n < 2)
        return -1;

    // Initialize maximum product with smallest possible value
    let maxProd = Number.MIN_SAFE_INTEGER;

    // Traverse all possible pairs
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // Calculate product of current pair
            let product = arr[i] * arr[j];

            // Update maximum product if needed
            maxProd = Math.max(maxProd, product);
        }
    }

    return maxProd;
}

// Driver Code 
    let arr = [1, 4, 3, 6, 7, 0];
    console.log(maxProduct(arr));

Output
42

Note: This approach also works correctly if the array contains negative numbers, since all possible pairs are considered.

[Better Approach] Using Sorting - O(n log n) Time and O(1) Space

The idea is to sort the array and then multiply the two largest elements. Since all elements are non-negative, the maximum product will always be obtained from the last two elements after sorting.

C++14
using namespace std;

int maxProduct(vector<int> &arr)
{
    int n= arr.size();
    
    // If less than 2 elements, no valid pair exists
    if (n < 2)
        return -1;

    // Sort the array
    sort(arr.begin(), arr.end());

    // Product of two largest elements
    int product = arr[n - 1] * arr[n - 2];

    return product;
}

int main()
{
    vector<int> arr = {1, 4, 3, 6, 7, 0};
    int n = arr.size();

    cout << maxProduct(arr);

    return 0;
}
Java
class GFG {

    static int maxProduct(int[] arr) {
        int n = arr.length;

        // If less than 2 elements, no valid pair exists
        if (n < 2)
            return -1;

        // Sort the array
        Arrays.sort(arr);

        // Product of two largest elements
        int product = arr[n - 1] * arr[n - 2];

        return product;
    }

    public static void main(String[] args) {
        int[] arr = {1, 4, 3, 6, 7, 0};
        System.out.println(maxProduct(arr));
    }
}
Python
def maxProduct(arr):
    n = len(arr)

    # If less than 2 elements, no valid pair exists
    if n < 2:
        return -1

    # Sort the array
    arr.sort()

    # Product of two largest elements
    product = arr[n - 1] * arr[n - 2]

    return product


if __name__ == "__main__":
    arr = [1, 4, 3, 6, 7, 0]
    print(maxProduct(arr))
C#
using System;

class GFG {

    static int maxProduct(int[] arr) {
        int n = arr.Length;

        // If less than 2 elements, no valid pair exists
        if (n < 2)
            return -1;

        // Sort the array
        Array.Sort(arr);

        // Product of two largest elements
        int product = arr[n - 1] * arr[n - 2];

        return product;
    }

    static void Main() {
        int[] arr = {1, 4, 3, 6, 7, 0};
        Console.WriteLine(maxProduct(arr));
    }
}
JavaScript
function maxProduct(arr) {
    let n = arr.length;

    // If less than 2 elements, no valid pair exists
    if (n < 2)
        return -1;

    // Sort the array
    arr.sort((a, b) => a - b);

    // Product of two largest elements
    let product = arr[n - 1] * arr[n - 2];

    return product;
}

//Drive code
    let arr = [1, 4, 3, 6, 7, 0];
    console.log(maxProduct(arr));

Output
42

Note: If the array contains negative numbers, the maximum product may not always come from the two largest elements. In such cases, also consider:

  • Product of the first two elements (smallest elements after sorting)
  • Product of the last two elements (largest elements)

Finally, return the maximum of: max(arr[0] * arr[1], arr[n-1] * arr[n-2])

[Expected Approach] Single Traversal - O(n) Time and O(1) Space

Instead of sorting the array, we can find the largest and second largest elements in a single traversal. The idea is to iterate through the array once and keep updating the two maximum values. This avoids the extra cost of sorting and improves efficiency.

Steps:

  • Initialize two variables: max1 -> largest element, max2 -> second largest element
  • Traverse the array: if current element is greater than max1, update both max1 and max2; else if it is greater than max2, update only max2
  • Return the product of max1 and max2.
C++
using namespace std;

// Function to find maximum product of two elements
int maxProduct(vector<int> &arr)
{
    int n = arr.size();

    // If less than 2 elements, no valid pair exists
    if (n < 2)
        return -1;

    // Initialize two variables to store largest and second largest
    int max1 = INT_MIN, max2 = INT_MIN;

    // Traverse the array
    for (int i = 0; i < n; i++)
    {
        int x = arr[i];

        // Update largest and second largest elements
        if (x > max1)
        {
            max2 = max1;
            max1 = x;
        }
        else if (x > max2)
        {
            max2 = x;
        }
    }

    return max1 * max2;
}

int main()
{
    vector<int> arr = {1, 4, 3, 6, 7, 0};
    cout << maxProduct(arr);
    return 0;
}
Java
class GFG {

    // Function to find maximum product of two elements
    static int maxProduct(int[] arr) {
        int n = arr.length;

        // If less than 2 elements, no valid pair exists
        if (n < 2)
            return -1;

        // Initialize largest and second largest
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;

        // Traverse the array
        for (int i = 0; i < n; i++) {
            int x = arr[i];

            // Update largest and second largest elements
            if (x > max1) {
                max2 = max1;
                max1 = x;
            } else if (x > max2) {
                max2 = x;
            }
        }

        return max1 * max2;
    }

    public static void main(String[] args) {
        int[] arr = {1, 4, 3, 6, 7, 0};
        System.out.println(maxProduct(arr));
    }
}
Python
# Function to find maximum product of two elements
def maxProduct(arr):
    n = len(arr)

    # If less than 2 elements, no valid pair exists
    if n < 2:
        return -1

    # Initialize largest and second largest
    max1 = float('-inf')
    max2 = float('-inf')

    # Traverse the array
    for i in range(n):
        x = arr[i]

        # Update largest and second largest elements
        if x > max1:
            max2 = max1
            max1 = x
        elif x > max2:
            max2 = x

    return max1 * max2

if __name__ == "__main__":
    arr = [1, 4, 3, 6, 7, 0]
    print(maxProduct(arr))
C#
using System;

class GFG {

    // Function to find maximum product of two elements
    static int maxProduct(int[] arr) {
        int n = arr.Length;

        // If less than 2 elements, no valid pair exists
        if (n < 2)
            return -1;

        // Initialize largest and second largest
        int max1 = int.MinValue, max2 = int.MinValue;

        // Traverse the array
        for (int i = 0; i < n; i++) {
            int x = arr[i];

            // Update largest and second largest elements
            if (x > max1) {
                max2 = max1;
                max1 = x;
            } else if (x > max2) {
                max2 = x;
            }
        }

        return max1 * max2;
    }

    static void Main() {
        int[] arr = {1, 4, 3, 6, 7, 0};
        Console.WriteLine(maxProduct(arr));
    }
}
JavaScript
// Function to find maximum product of two elements
function maxProduct(arr) {
    let n = arr.length;

    // If less than 2 elements, no valid pair exists
    if (n < 2)
        return -1;

    // Initialize largest and second largest
    let max1 = Number.MIN_SAFE_INTEGER;
    let max2 = Number.MIN_SAFE_INTEGER;

    // Traverse the array
    for (let i = 0; i < n; i++) {
        let x = arr[i];

        // Update largest and second largest elements
        if (x > max1) {
            max2 = max1;
            max1 = x;
        } else if (x > max2) {
            max2 = x;
        }
    }

    return max1 * max2;
}

// Driver Code
    let arr = [1, 4, 3, 6, 7, 0];
    console.log(maxProduct(arr));

Output
42

Note: If Array Contains Negative Numbers

The above approach works efficiently when all elements are non-negative. However, if the array contains negative numbers, the maximum product may not always be obtained from the two largest elements.

This is because the product of two negative numbers is positive and can be greater than the product of two large positive numbers.

To handle such cases, also consider: Product of the two largest elements and Product of the two smallest elements (most negative)

Finally, return the maximum of the two: max(max1 * max2, min1 * min2)

C++
using namespace std;

// Function to find maximum product of two elements
int maxProduct(vector<int> &arr)
{
    int n = arr.size();

    // If less than 2 elements, no valid pair exists
    if (n < 2)
        return -1;

    // Initialize largest and second largest
    int max1 = INT_MIN, max2 = INT_MIN;

    // Initialize smallest and second smallest
    int min1 = INT_MAX, min2 = INT_MAX;

    // Traverse the array
    for (int i = 0; i < n; i++)
    {
        int x = arr[i];

        // Update largest elements
        if (x > max1)
        {
            max2 = max1;
            max1 = x;
        }
        else if (x > max2)
        {
            max2 = x;
        }

        // Update smallest elements
        if (x < min1)
        {
            min2 = min1;
            min1 = x;
        }
        else if (x < min2)
        {
            min2 = x;
        }
    }

    return max(max1 * max2, min1 * min2);
}

int main()
{
    vector<int> arr = {-1, -3, -4, 2, 0, -5};
    cout << maxProduct(arr);
    return 0;
}
Java
class GFG {

    // Function to find maximum product of two elements
    static int maxProduct(int[] arr) {
        int n = arr.length;

        // If less than 2 elements, no valid pair exists
        if (n < 2)
            return -1;

        // Initialize largest and second largest
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;

        // Initialize smallest and second smallest
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;

        // Traverse the array
        for (int i = 0; i < n; i++) {
            int x = arr[i];

            // Update largest elements
            if (x > max1) {
                max2 = max1;
                max1 = x;
            } else if (x > max2) {
                max2 = x;
            }

            // Update smallest elements
            if (x < min1) {
                min2 = min1;
                min1 = x;
            } else if (x < min2) {
                min2 = x;
            }
        }

        return Math.max(max1 * max2, min1 * min2);
    }

    public static void main(String[] args) {
        int[] arr = {-1, -3, -4, 2, 0, -5};
        System.out.println(maxProduct(arr));
    }
}
Python
# Function to find maximum product of two elements
def maxProduct(arr):
    n = len(arr)

    # If less than 2 elements, no valid pair exists
    if n < 2:
        return -1

    # Initialize largest and second largest
    max1 = float('-inf')
    max2 = float('-inf')

    # Initialize smallest and second smallest
    min1 = float('inf')
    min2 = float('inf')

    # Traverse the array
    for i in range(n):
        x = arr[i]

        # Update largest elements
        if x > max1:
            max2 = max1
            max1 = x
        elif x > max2:
            max2 = x

        # Update smallest elements
        if x < min1:
            min2 = min1
            min1 = x
        elif x < min2:
            min2 = x

    return max(max1 * max2, min1 * min2)


if __name__ == "__main__":
    arr = [-1, -3, -4, 2, 0, -5]
    print(maxProduct(arr))
C#
using System;

class GFG {

    // Function to find maximum product of two elements
    static int maxProduct(int[] arr) {
        int n = arr.Length;

        // If less than 2 elements, no valid pair exists
        if (n < 2)
            return -1;

        // Initialize largest and second largest
        int max1 = int.MinValue, max2 = int.MinValue;

        // Initialize smallest and second smallest
        int min1 = int.MaxValue, min2 = int.MaxValue;

        // Traverse the array
        for (int i = 0; i < n; i++) {
            int x = arr[i];

            // Update largest elements
            if (x > max1) {
                max2 = max1;
                max1 = x;
            } else if (x > max2) {
                max2 = x;
            }

            // Update smallest elements
            if (x < min1) {
                min2 = min1;
                min1 = x;
            } else if (x < min2) {
                min2 = x;
            }
        }

        return Math.Max(max1 * max2, min1 * min2);
    }

    static void Main() {
        int[] arr = {-1, -3, -4, 2, 0, -5};
        Console.WriteLine(maxProduct(arr));
    }
}
JavaScript
// Function to find maximum product of two elements
function maxProduct(arr)
{
    let n = arr.length;

    // If less than 2 elements, no valid pair exists
    if (n < 2)
        return -1;

    // Initialize largest and second largest
    let max1 = Number.MIN_SAFE_INTEGER;
    let max2 = Number.MIN_SAFE_INTEGER;

    // Initialize smallest and second smallest
    let min1 = Number.MAX_SAFE_INTEGER;
    let min2 = Number.MAX_SAFE_INTEGER;

    // Traverse the array
    for (let i = 0; i < n; i++) {
        let x = arr[i];

        // Update largest elements
        if (x > max1) {
            max2 = max1;
            max1 = x;
        }
        else if (x > max2) {
            max2 = x;
        }

        // Update smallest elements
        if (x < min1) {
            min2 = min1;
            min1 = x;
        }
        else if (x < min2) {
            min2 = x;
        }
    }

    return Math.max(max1 * max2, min1 * min2);
}

// Driver Code
let arr = [ -1, -3, -4, 2, 0, -5 ];
console.log(maxProduct(arr));

Output
20
Comment