Find the Maximum Product of Two Integers in an Array

Problem Statement: Given an array of integers, find the maximum product of any two distinct integers in the array.

Steps:

  1. Initialize two variables, max1 and max2, to store the two largest integers found so far. Initialize them to the minimum possible value.

  2. Iterate through the array:

    • For each element, update max1 and max2 accordingly.
  3. The maximum product will be max1 * max2.

Time Complexity:

  • O(n), where n is the number of elements in the array.

Space Complexity:

  • O(1), as we are using a constant amount of space.

C++ Implementation:

#include <iostream>
using namespace std;

int maxProduct(int arr[], int n) {
    if (n < 2) return 0; // Not enough elements

    int max1 = INT_MIN;
    int max2 = INT_MIN;

    for (int i = 0; i < n; i++) {
        if (arr[i] > max1) {
            max2 = max1;
            max1 = arr[i];
        } else if (arr[i] > max2) {
            max2 = arr[i];
        }
    }
    return max1 * max2;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Maximum product: " << maxProduct(arr, n) << endl;
    return 0;
}

Java Implementation:

public class MaxProduct {
    public static int maxProduct(int[] arr) {
        if (arr.length < 2) return 0;

        int max1 = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;

        for (int num : arr) {
            if (num > max1) {
                max2 = max1;
                max1 = num;
            } else if (num > max2) {
                max2 = num;
            }
        }
        return max1 * max2;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("Maximum product: " + maxProduct(arr));
    }
}

Python Implementation:

def max_product(arr):
    if len(arr) < 2:
        return 0  # Not enough elements

    max1 = float('-inf')
    max2 = float('-inf')

    for num in arr:
        if num > max1:
            max2 = max1
            max1 = num
        elif num > max2:
            max2 = num

    return max1 * max2

arr = [1, 2, 3, 4, 5]
print("Maximum product:", max_product(arr))