Pythonic方式优雅修复滑动窗口解LeetCode股票买卖II的索引越界问题
「买卖股票的最佳时机II」滑动窗口法报错与优化讨论
题目基本信息
- 题目名称:LeetCode 买卖股票的最佳时机II
- 题目链接:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ - 题目描述:给定数组
prices,其中prices[i]为第i天的股票价格,计算完成任意次交易(可多次买入、卖出同一只股票)时能获得的最大收益。 - 示例说明:
- 输入:
prices = [7,1,5,3,6,4] - 输出:
7 - 解释:第2天(价格1)买入、第3天(价格5)卖出,获利润4;第4天(价格3)买入、第5天(价格6)卖出,获利润3,合计总利润7。
- 输入:
报错情况与初步修复
- 采用滑动窗口方法解题时遇到IndexError,排查后确认错误根源为:窗口右边界
j(取值为idx+1)在遍历过程中最大可能超出数组合法下标范围,需要Pythonic风格的优雅修复方案。 - 最初编写的代码如下:
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: totalProfit = 0 currentProfit = 0 for idx, x in enumerate(prices): j = idx + 1 while prices[j] > prices[idx] and prices[j] > prices[j-1]: currentProfit = prices[j] - prices[idx] totalProfit += currentProfit j += 1 return totalProfit
- 运行时报错信息:
IndexError: list index out of range while prices[j] > prices[idx] and prices[j] > prices[j-1]:
初步修复代码与待优化点
- 参考@Prune的建议,在进入循环判断前检查
j是否超出边界,若j达到数组长度则跳出迭代,更新后的代码可通过示例输入,但尚未覆盖全部边界测试场景,仍有优化空间。 - 更新后的代码如下:
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: totalProfit = 0 currentProfit = 0 for idx, x in enumerate(prices): j = idx + 1 # 边界判断:j到达数组长度时直接跳出循环 if j == len(prices): break # 价格持续上涨时计算区间利润 elif prices[j] > prices[idx] and prices[j] > prices[j-1]: currentProfit = prices[j] - prices[idx] # 计算当前段利润 totalProfit += currentProfit # 累加总利润 j += 1 # 扩大窗口右边界 return totalProfit
内容的提问来源于stack exchange,提问作者yinqi
相关产品推荐
相关产品推荐

