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

LeetCode 121题提交报错:None非法整数返回值问题排查

LeetCode 121 买卖股票的最佳时机运行时错误分析

问题背景

我在解决LeetCode 121题(买卖股票的最佳时机):给定数组prices,prices[i]代表第i天的股票价格,需要选择一天买入、未来某一天卖出以最大化利润,无法获利则返回0。示例输入prices = [7,1,5,3,6,4],输出应为5。

我的代码在PyCharm中运行正常,LeetCode控制台的stdout也能打印正确结果,但提交时出现运行时错误:

TypeError: None is not valid value for the expected return type integer
raise TypeError(str(ret) + " is not valid value for the expected return type integer");
Line 46 in _driver (Solution.py)
_driver()
Line 53 in (Solution.py)
During handling of the above exception, another exception occurred:
TypeError: '<' not supported between instances of 'int' and 'NoneType'
Line 14 in _serialize_int (./python3/serializer.py)
Line 63 in _serialize (./python3/serializer.py)
out = ser._serialize(ret, 'integer')
Line 44 in _driver (Solution.py)

我的代码如下:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        temp = prices
        nprofit = temp[0]

        for j in range(len(temp) - 1):
            if temp[j] > temp[j + 1]:
                nprofit = temp[j]

        if nprofit == temp[len(temp) - 1]:
            return 0
        else:
            for i in range(len(temp)):
                smallest = min(temp)

                if temp.index(smallest) == len(temp) - 1:
                    temp.remove(smallest)
                else:
                    largest = max(temp[temp.index(smallest) + 1:])
                    print(largest - smallest)
                    profit = largest - smallest
                    return int(profit)

为什么会出现这个错误?


错误原因

你的代码存在返回值缺失的情况:当某些输入场景下,函数执行完所有逻辑后没有触发任何return语句,导致默认返回None,而LeetCode要求必须返回整数,因此触发类型错误。

举个典型的触发场景:输入prices = [5,4,3,2,1](完全递减的数组):

  1. 第一个循环遍历后,nprofit最终为2,不等于最后一天的价格1,进入else块。
  2. 循环中不断移除位于数组末尾的最小值,直到数组被清空。
  3. 循环结束后没有任何return语句,函数返回None,不符合LeetCode的返回类型要求。

另外,你的第一个判断逻辑完全错误,它根本无法准确判断是否“无法获利”,比如完全递减的数组会错误进入else块,进一步触发返回值缺失的问题。


修正方案

1. 紧急修复返回值问题

在else块的循环结束后添加return 0,确保所有路径都有返回值:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        temp = prices.copy()  # 改为拷贝,避免修改原数组
        nprofit = temp[0]

        for j in range(len(temp) - 1):
            if temp[j] > temp[j + 1]:
                nprofit = temp[j]

        if nprofit == temp[len(temp) - 1]:
            return 0
        else:
            for i in range(len(temp)):
                smallest = min(temp)
                idx = temp.index(smallest)
                if idx == len(temp) - 1:
                    temp.remove(smallest)
                else:
                    largest = max(temp[idx + 1:])
                    profit = largest - smallest
                    return profit
            return 0  # 新增:循环结束后返回0

2. 优化为正确高效的逻辑

原代码逻辑复杂且存在漏洞,推荐使用更简洁的O(n)时间复杂度解法:遍历数组时记录当前最小买入价,同时计算当前利润并维护最大利润:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        min_price = prices[0]
        max_profit = 0
        for price in prices[1:]:
            if price < min_price:
                min_price = price
            else:
                current_profit = price - min_price
                if current_profit > max_profit:
                    max_profit = current_profit
        return max_profit

这个逻辑能覆盖所有场景:

  • 完全递减数组时,max_profit保持0,正确返回0。
  • 存在上涨区间时,动态更新最小买入价和最大利润。
  • 所有分支都有明确的返回值,不会出现None的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:44:51