查找具有最大乘积的数组子集

时间:2020-02-05 05:00:42

标签: python python-2.7

我收到了面试问题,以找到具有最大乘积的数组的非空子集。我解决了任务,但五分之一没有通过。我不明白我在解决方案中可能错过了什么。 (该任务应在python 2.7中完成)

任务在这里:

我有一个整数数组,我需要返回具有最大乘积的元素的非空子集。如果数组中有奇数个负数,则必须排除其中一个,以使所选乘积为正。

如果我内部有0,通常我也想排除它。例如:对于[2,5,-2]结果应为10,对于[-2,-5,-1,0,2]结果应为20。

我尝试了不同的边缘情况,例如[-1],[1],[0],[0,0,0]

解决方案在这里:

from functools import reduce

def answer(arr):
    selection = [n for n in arr if n !=0 and -1000<=n<=1000]
    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 str(reduce(lambda x, y: x * y, selection))

1 个答案:

答案 0 :(得分:2)

仔细阅读该问题表明answer([-5])应该产生解决方案-5,因为它需要选择输入数组的一个非空子集。但是,您的代码为answer([-5])返回0。所以也许像这样:

from functools import reduce

def answer(arr):
    hasZero = any([n == 0 for n in arr])
    selection = [n for n in arr if n !=0 and -1000<=n<=1000]
    negative = [n for n in selection if n<0]
    if len(negative) % 2 == 1 and (len(selection) > 1 or hasZero):
        selection.remove(max(negative))
    if not selection:
        return '0'
    else:
        return str(reduce(lambda x, y: x * y, selection))

answer([-5])
# '-5'
answer([0, -5])
# '0'