【发布时间】:2021-10-25 05:19:11
【问题描述】:
我正在尝试解决 Leetcode (121.Best Time to Buy and Sell Stock) 问题,我想到的第一个(蛮力)方法是以下代码。
我原以为代码的逻辑没有问题,代码的思路看起来和官方的解决方案很相似,但是由于某种原因,我的代码出现了 Memory Limit Exceeded 错误。我不想使用调试器,因为在实际的面试环境中我将无法使用调试器,我想练习思考为什么代码可能只是理论上的错误,但我在这里遇到了麻烦。有人可以帮我弄清楚/给我提示我可能在哪里出错吗?
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
brute force way:
for every element in the list, go through every other element after that element and find their
differences; store all differences in a single array "profit", and find max
"""
profit = []
if len(prices) > 1:
for i in range(len(prices)):
for j in range(i+1, len(prices)):
profit.append(prices[j] - prices[i])
if len(profit) >= 1:
profitt = max(profit)
return max(0, profitt)
else:
return 0
【问题讨论】:
-
我认为您实际上没有在此处提供必要的代码示例。你所展示的只是一个类定义,除了描述一个类之外,它什么都不做。现在,你如何使用这个类?你那里的逻辑是什么?在循环、递归函数或处理过多数据期间会出现内存不足异常问题。如果没有实际的程序逻辑,就不可能说出您的问题可能是什么。
-
这个问题可能会被关闭,但为了提供一些有用的建议,您需要研究 Big-O 复杂性——尤其是当您的代码中有嵌套循环时,您不这样做' t 对输入大小有预先的启发式方法。最明显的蛮力算法经常在大输入时失败——有时甚至是惊人的失败。这就是你需要在这里为这个问题培养的直觉。
-
在这里思考
Kadane算法——如何在每一步本地找到maxProfit。
标签: python arrays dynamic-programming