Warm tip: This article is reproduced from stackoverflow.com, please click
algorithm max python

Find a maximum possible value of an array

发布于 2020-04-13 09:43:30

I have an array of integers and I need to get their maximum possible value. If I have negative numbers and their total amount is uneven I have to exclude one of them to make an array positive.

If I have 0 inside and it can affect on result of my multiplication, I have to exclude it also. For example: for [2, 5, -2] result should be 10, for [-2,-5,-1, 0, 2] result should be 20.

I implemented the task, but the system doesn't accept my solution, could you please take a look at my solution where I could make a mistake? I tried different edge cases like [-1], [1], [0], [0,0,0]

def answer(n):
    arr = 0
    res = 1
    for number in n:
        if number < 0:
            arr += 1
    n.sort()
    while 0 in n: n.remove(0)
    if not n:
        return '0'
    if len(n) == 1:
        if n[0] < 0:
            return '0'
    elif arr % 2 != 0:
        n.pop(arr - 1)
    for x in n:
        res *= x
    return str(res)
Questioner
JohnPix
Viewed
14
Grismar 2020-02-03 18:09

It appears you are looking to multiply all numbers in a list, except for any zeroes and if there's an odd number of negative numbers, you are excluding the smallest negative number?

A simple solution:

from functools import reduce


def answer(numbers):
    selection = [n for n in numbers if n != 0]
    negative = [n for n in selection if n < 0]
    if len(negative) % 2 == 1:
        selection.remove(max(negative))
    if not selection:
        return 0
    else:
        return reduce(lambda x, y: x * y, selection)


print(answer([-2, -5, -1, 0, 2]))