Given an array
aa, find the greatest number inaa that is a product of two elements inaa. If there are no two elements inaa that can be multiplied to produce another element contained in a, return -1.
I am trying to get this to run as fast as possible. I assume there is some math algorithm or formula to do this that I am unaware of. This is the way I know how to find this answer. However, I assume this would take a long time if the length of the array was huge. Is there a faster way to do this? I have provided the test.
using System;
using System.Linq;
namespace Exercise
{
public static class Program
{
public static int maxPairProduct(int[] a)
{
int x = -1;
for (int i = 0; i < a.Length; ++i)
{
for (int j = i + 1; j < a.Length; ++j)
{
int temp = a[i] * a[j];
if (a.Contains(temp) && temp > x)
{
x = temp;
}
}
}
return x;
}
}
}
using NUnit.Framework;
namespace Exercise
{
public class SuccessTests
{
[Test]
public static void TestOne() => Assert.That(Program.maxPairProduct(new int[] { 10, 3, 5, 30, 35 }), Is.EqualTo(30));
public static void TestTwo() => Assert.That(Program.maxPairProduct(new int[] { 2, 5, 7, 8 }), Is.EqualTo(-1));
}
}
```