我想出了下面的代碼,但是這並不能滿足所有的情況下,例如連續序列:找到在整數數組最大的產品
陣列,其中包括全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