You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组整数最大乘积求解:现有Python代码部分测试用例未通过

数组最大乘积问题的代码漏洞及修复方案

你的思路方向是对的——通过计算非零元素乘积,若负数个数为奇数则移除绝对值最小的负数(即最大的负数)来获取最大乘积,但代码遗漏了几种边界场景,导致部分测试用例失败:

原代码的核心问题

  • 全0数组未处理:例如[0,0,0],原代码会返回"1",但实际最大乘积应为0。
  • 单负数+多0场景错误:例如[-5,0,0],原代码返回"1",但正确结果应为0(选择0而非负数)。
  • 浮点数结果问题:使用除法/会让整数结果变成浮点数(如1变成1.0),返回的字符串格式不符合预期。

修复后的代码

def solution(xs):
    # 处理单元素数组
    if len(xs) == 1:
        return str(xs[0])
    
    # 分类存储正、负、零元素
    positives = [num for num in xs if num > 0]
    negatives = [num for num in xs if num < 0]
    zeros = [num for num in xs if num == 0]
    
    product = 1
    # 计算所有正数的乘积
    for num in positives:
        product *= num
    
    # 处理负数部分
    if len(negatives) > 0:
        negatives.sort()
        if len(negatives) % 2 == 0:
            # 偶数个负数,全部相乘
            for num in negatives:
                product *= num
        else:
            # 奇数个负数,去掉绝对值最小的那个(排序后的最后一个元素)
            if len(negatives) > 1:
                for num in negatives[:-1]:
                    product *= num
            else:
                # 只有一个负数且无正数时,取0作为结果(如果有零)
                if zeros:
                    product = 0
    
    # 处理无有效正数/负数乘积的情况
    if product == 1 and not positives and len(negatives) <= 1:
        product = 0 if zeros else (negatives[0] if negatives else 0)
    
    return str(product)

修复说明

  1. 分类处理元素:将数组拆分为正数、负数、零,逻辑更直观,便于边界场景判断。
  2. 全0场景覆盖:当无有效正/负数乘积时,直接返回0。
  3. 单负数+零场景修正:此时优先选择0作为最大乘积,而非错误的1。
  4. 整数结果保证:通过切片移除负数而非除法,避免产生浮点数,返回的字符串为整数格式。
  5. 排序简化操作:对负数数组排序后,可快速定位并移除绝对值最小的负数(即排序后的最后一个元素)。

内容的提问来源于stack exchange,提问作者Seb Heron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:45:48