题目
代码
执行用时:4532 ms, 在所有 Python3 提交中击败了5.03% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了29.51% 的用户
通过测试用例:200 / 200
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit=0
for i in range(len(prices)):
if i+1<len(prices):
max_profit=max(max_profit,max(prices[i+1:])-prices[i])
return max_profit
【方法2】
执行用时:52 ms, 在所有 Python3 提交中击败了17.09% 的用户
内存消耗:15.6 MB, 在所有 Python3 提交中击败了57.31% 的用户
通过测试用例:200 / 200
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
high=[prices[-1]]*len(prices)
index=len(prices)-2
while index>=0:
high[index]=max(prices[index],high[index+1])
index-=1
ans=0
for i in range(len(prices)-1):
ans=max(ans,high[i+1]-prices[i])
return ans
【方法3】
执行用时:40 ms, 在所有 Python3 提交中击败了65.62% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了39.41% 的用户
通过测试用例:200 / 200
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:return 0
ans=0
min_num=prices[0]
for i in range(1,len(prices)):
min_num=min(min_num,prices[i])
ans=max(ans,prices[i]-min_num)
return ans

这篇博客探讨了三种不同的Python代码实现来求解股票最大利润问题。方法1使用了简单的循环,方法2通过构建最高价格数组优化了时间复杂度,而方法3通过跟踪最低价格来减少计算。所有方法均通过了200个测试用例,并在执行时间和内存使用上有所不同。
403

被折叠的 条评论
为什么被折叠?



