# 在整數數組中查找具有最大乘積的連續序列

1. Array consisting all 0's

2. Array having negative values(it's bit tricky since it's about finding product as two negative ints give positive value)

public static int LargestProduct(int[] arr)
{
//returning arr[0] if it has only one element
if (arr.Length == 1) return arr[0];

int product = 1;
int maxProduct = Int32.MinValue;

for (int i = 0; i < arr.Length; i++)
{
//this block store the largest product so far when it finds 0
if (arr[i] == 0)
{
if (maxProduct < product)
{
maxProduct = product;
}
product = 1;
}
else
{
product *= arr[i];
}
}
if (maxProduct > product)
return maxProduct;
else
return product;
}


## 最佳答案

n個整數數組中的乘積總數為nC2，即如果有2個元素，那麽總乘法組合將是1，對於3，它將是3，對於4，它將是6，依此類推。

    public static long LargestProduct(int[] arr)
{
if (arr.Length == 1)
return arr[0];

int lastNumber = 1;
List latestProducts = new List();
long maxProduct = Int64.MinValue;
for (int i = 0; i < arr.Length; i++)
{
var item = arr[i];
var latest = lastNumber * item;
var temp = new long[latestProducts.Count];
latestProducts.CopyTo(temp);
latestProducts.Clear();
foreach (var p in temp)
{
var product = p * item;
if (product > maxProduct)
maxProduct = product;
}
if (i != 0)
{
if (latest > maxProduct)
maxProduct = latest;
}
lastNumber = item;
}
return maxProduct;
}


if (item > maxProduct)
maxProduct = item;