Question

Here is the question.

      Given an array of integers and a length L, find a sub-array of length L 
      such that the products of all integers are the biggest.
      Example:
      Input:  {4, 1, -7, -8, 9, 2, 0, 5}, 3
      Output: {-7,-8,9}

I am almost done, I can get the biggest product but the array itself.

    static void Main(string[] args)
    {
        int[] array = { 4, 1, -7, -8, 9, 2, 0, 5 };
        int L = 3;
        int max = Int32.MinValue;
        for (int i = 0; i <= array.Length - L; i++)
        {
            var subArray = new ArraySegment<int>(array, i, L);
            var product = subArray.Aggregate((a, b) => a * b);
            if (product > max)
                max = product;
        }          
        Console.WriteLine(max); // Help: I need to output the sub-array.
        Console.Read();
    }
Was it helpful?

Solution

Assuming that your logic to get biggest product is correct already, you can simply have additional variable maxSubArray that works in similar way as max variable :

int[] array = { 4, 1, -7, -8, 9, 2, 0, 5 };
int L = 3;
int max = Int32.MinValue;
ArraySegment<int> maxSubArray = new ArraySegment<int>();
for (int i = 0; i <= array.Length - L; i++)
{
    var subArray = new ArraySegment<int>(array, i, L);
    var product = subArray.Aggregate((a, b) => a * b);
    if (product > max)
    {
        max = product;
        maxSubArray = subArray;
    }
}
Console.WriteLine(max);
foreach (var i in maxSubArray)
{
    Console.WriteLine(i);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top