Search⌘ K
AI Features

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

Explore methods to determine the maximum product of two integers in an array. This lesson teaches you a brute force method with O(n^2) complexity and a more efficient single-pass technique with O(n) complexity, helping you optimize your C# coding solutions for interviews.

Solution 1: Brute force approach

C# 9.0
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. If it is greater than maxProduct, we update the value of maxProduct and store the indexes of the array in i and j.

Time complexity

The ...