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

计算数组非相邻元素最大和时,方法内循环到数组末尾中断的实现

代码修改方案

你可以参考以下修改,在原有实现思路基础上新增少量代码完成需求:

def nextMaximum(indexOfCurrentMax, array): 
    # 边界判断:超出数组长度的位置取值为0
    val_2 = array[indexOfCurrentMax + 2] if indexOfCurrentMax + 2 < len(array) else 0
    val_3 = array[indexOfCurrentMax + 3] if indexOfCurrentMax + 3 < len(array) else 0
    if val_2 == 0 and val_3 == 0:
        # 无有效下一个元素,返回结束标识
        return None
    # 同时返回最大值和对应索引,方便更新位置
    return (val_2, indexOfCurrentMax + 2) if val_2 > val_3 else (val_3, indexOfCurrentMax + 3)

def maxSubsetSumNoAdjacent(array):
    # 兼容数组长度小于2的边界场景
    if len(array) == 0:
        return 0
    if len(array) == 1:
        return array[0]
    total = 0 
    indexOfCurrentMax = array.index(max(array[0],array[1]))
    total += array[indexOfCurrentMax]
    
    # 新增循环逻辑
    while True:
        next_info = nextMaximum(indexOfCurrentMax, array)
        if next_info is None:
            # 遍历到数组末尾,跳出循环
            break
        current_max, next_index = next_info
        total += current_max
        indexOfCurrentMax = next_index
    return total

# 测试示例
array = [75,105,120,75,90,135]
print(maxSubsetSumNoAdjacent(array)) # 输出330

核心改动说明

  • 调整nextMaximum方法:新增数组入参、索引越界判断,返回值新增最大值对应的索引,避免主方法无法定位下一个起始位置
  • 主方法新增边界兼容逻辑,处理数组长度小于2的异常场景
  • 新增while循环:每次拉取下一个可选的最大值,当无有效可选值时自动中断循环,完成全数组遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:00:06