📜  用于数组的最小乘积子集的Python程序

📅  最后修改于: 2022-05-13 01:55:16.754000             🧑  作者: Mango

用于数组的最小乘积子集的Python程序

给定一个数组 a,我们必须找到数组中存在的元素子集的最小乘积。最小乘积也可以是单个元素。

例子:

Input : a[] = { -1, -1, -2, 4, 3 }
Output : -24
Explanation : Minimum product will be ( -2 * -1 * -1 * 4 * 3 ) = -24

Input : a[] = { -1, 0 }
Output : -1
Explanation : -1(single element) is minimum product possible
 
Input : a[] = { 0, 0, 0 }
Output : 0

一个简单的解决方案是生成所有子集,找到每个子集的乘积并返回最小乘积。
更好的解决方案是使用以下事实。

  1. 如果有偶数个负数且没有零,则结果是除最大值负数之外的所有负数的乘积。
  2. 如果有奇数个负数并且没有零,则结果只是所有的乘积。
  3. 如果有零和正数,没有负数,则结果为 0。例外情况是当没有负数且所有其他元素为正数时,我们的结果应该是第一个最小正数。
Python3
# Python3 program to find maximum
# product of a subset.
  
# def to find maximum
# product of a subset
  
  
def minProductSubset(a, n):
    if (n == 1):
        return a[0]
  
    # Find count of negative numbers,
    # count of zeros, maximum valued
    # negative number, minimum valued
    # positive number and product
    # of non-zero numbers
    max_neg = float('-inf')
    min_pos = float('inf')
    count_neg = 0
    count_zero = 0
    prod = 1
    for i in range(0, n):
  
        # If number is 0, we don't
        # multiply it with product.
        if (a[i] == 0):
            count_zero = count_zero + 1
            continue
  
        # Count negatives and keep
        # track of maximum valued
        # negative.
        if (a[i] < 0):
            count_neg = count_neg + 1
            max_neg = max(max_neg, a[i])
  
        # Track minimum positive
        # number of array
        if (a[i] > 0):
            min_pos = min(min_pos, a[i])
  
        prod = prod * a[i]
  
    # If there are all zeros
    # or no negative number
    # present
    if (count_zero == n or (count_neg == 0
                            and count_zero > 0)):
        return 0
  
    # If there are all positive
    if (count_neg == 0):
        return min_pos
  
    # If there are even number of
    # negative numbers and count_neg
    # not 0
    if ((count_neg & 1) == 0 and
            count_neg != 0):
  
        # Otherwise result is product of
        # all non-zeros divided by
        # maximum valued negative.
        prod = int(prod / max_neg)
  
    return prod
  
  
# Driver code
a = [-1, -1, -2, 4, 3]
n = len(a)
print(minProductSubset(a, n))
# This code is contributed by
# Manish Shaw (manishshaw1)


输出:
-24

时间复杂度: O(n)
辅助空间: O(1)

有关更多详细信息,请参阅有关数组的最小产品子集的完整文章!