我想出了下面的代码,但是这并不能满足所有的情况下,例如连续序列:找到在整数数组最大的产品
阵列,其中包括全0
具有负值阵列(它的位棘手,因为它是寻找产物两个负整数给出正值)
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; }
如何合并上述案例/更正代码。请建议。
感谢提出的解决方案,但上面的代码简化版,为下面的数组使用负值。 {-1,-15,-30,0,-17,2}:它应该返回450作为最大的产品,但它返回15. – 2011-05-12 17:25:15
@bhakti,'-1 * -15 * -30'是'-450 '。另外,这应该是对这个答案的评论。 – 2011-05-12 17:28:19
我真的很抱歉,因为我是用智能手机发布的。我试图在Nikita的帖子下找到'add comment'链接,但找不到一个。在上面的负数组中,代码应该返回-15 * -30的产品,因为这是返回最大产品的传染性元素 – 2011-05-12 17:43:58