Home > Enterprise >  Find the product of numbers in an array
Find the product of numbers in an array

Time:10-05

I need to find the largest product from an array of numbers. So [-2, -3, 4, -5] would return 60, because (-5)(4)(-3)=60

I've come up with the following code so far, and this passes the above test case but fails for some hidden edge cases.

def largest_product(arr):
    negatives = sorted([n for n in arr if n < 0])
    positive_product = negative_product = 1

    if len(negatives) % 2 != 0 and len(arr) > 1 and len(negatives) > 1:
        negatives.pop()

    for n in arr:
        positive_product *= n if n > 0 else 1

    for n in negatives:
        negative_product *= n

    return str(positive_product * negative_product)

I'm thinking something along the lines of

  1. Get the product of all positive integers. (because they always produce the greatest result)
  2. Filter and sort the negative integers.
  3. If the number of negative integers is even, multiply them to get the final product.
  4. If the number of negative integers is odd, then remove the smallest / last integer and do step 3.

What am I missing here?

CodePudding user response:

Here are some test cases that fail:

[-5, 8]
[-5, 0]
[-1, 0, 2]
[0]

Some issues:

  • The condition len(negatives) > 1 is not correct. If len(negatives) == 1 then you certainly don't want to use that negative value in a product unless it is it the only value in the array.

  • The default value of 1 for the positive product is wrong when the only non-negative value is 0.

  • Not sure why you convert the product to a string...

Here is a correction:

def largest_product(arr):
    if not arr:  # No choice => no product
        return  
    if len(arr) == 1:  # One choice => take it
        return arr[0]
        
    negatives = sorted([n for n in arr if n < 0])
    positive_product = negative_product = 1

    if len(negatives) % 2 != 0:  # corrected condition
        negatives.pop()

    if max(arr) == 0 and not negatives:  # special case
        return 0

    for n in arr:
        positive_product *= n if n > 0 else 1

    for n in negatives:
        negative_product *= n

    return positive_product * negative_product
  • Related