...

/

Solution: Find the Maximum Product of Two Integers in an Array

Solution: Find the Maximum Product of Two Integers in an Array

Explore various approaches to solving the challenge of finding the maximum product of two integers in an array of numbers.

Solution 1: Brute force approach

using System;
class Program
{
/// <summary>
/// Finds the pair having maximum product in a given array.
/// </summary>
/// <param name="arr">An array of integers.</param>
// <returns>A pair of integers.</returns>
public static Tuple<int, int> FindMaxProduct(int[] arr)
{
int maxProduct = int.MinValue;
int maxI = -1;
int maxJ = -1;
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length; j++)
{
if (maxProduct < arr[i] * arr[j] && i != j)
{
maxProduct = arr[i] * arr[j];
maxI = arr[i];
maxJ = arr[j];
}
}
}
return Tuple.Create(maxI, maxJ);
}
// Driver to test above code
static void Main(string[] args)
{
int[] arr = { 1, 3, 5, 2, 6 };
Tuple<int, int> result = FindMaxProduct(arr);
Console.WriteLine(result.Item1 + ", " + result.Item2);
}
}

Explanation

In this solution, we calculate the product of each element of the array with every other element except for the element itself. Every time we calculate the product, we compare it with the previous stored product in maxProduct ...