【发布时间】:2021-03-22 21:57:59
【问题描述】:
我正在使用滑动窗口做这个 leetcode 问题,我意识到我得到了 IndexError,因为可以得到的最大值 j (= idx+1) 超出了范围。我想知道是否有一种优雅的方法来解决它?
链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
问题陈述:
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
输入输出示例:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
这是我的代码:
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 在进入下一次迭代之前超出边界时,我会中断循环。它适用于示例输入,但我没有用极端情况测试它。让我们讨论一下是否还有改进的余地!
这是更新后的代码:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
totalProfit = 0
currentProfit = 0
for idx, x in enumerate(prices):
j = idx+1
if j == len(prices): # boundary: break before entering loop
break
elif prices[j] > prices[idx] and prices[j] > prices[j-1]: # when continue to increase, enter loop
currentProfit = prices[j] - prices[idx] # return value
totalProfit += currentProfit # sum and return
j += 1 #increase window size
return totalProfit
【问题讨论】:
-
请提供预期的minimal, reproducible example (MRE)。我们应该能够复制并粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和所需的输出来测试我们的建议。
-
一般来说,解决这个问题的优雅方法是在进入循环之前计算正确的边界;仅在合法范围内进行迭代。这是基本代数;你到底卡在哪里了?由于您未能提供完整的错误消息和正确的跟踪,我们必须正确检测和运行您的代码以获取所需的信息。这是你的任务。
-
你不需要一个类,一个简单的函数就足够了,因为你在这段代码中没有任何状态。您是 Java 开发人员吗?