这是一个问题。
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}
我差不多完成了,我可以获得最大的产品,但阵列本身。
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();
}
答案 0 :(得分:0)
假设您获得最大产品的逻辑已经正确,您可以简单地使用与maxSubArray
变量类似的其他变量max
:
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);
}