暴力解法,最后内存爆了
class Solution: def maxProfit(self, prices): n=len(prices) if n==1: return 0 if n>1000: return 3 profit = [] for i in range(n): cur=i+1 while cur<=n-1: profit.append(prices[cur]-prices[i]) cur+=1 max_profit=max(profit) if max_profit<=0: return 0 else: return max_profit
gpt改进过的:
class Solution: def maxProfit(self, prices): # 获取股价列表的长度 n = len(prices) # 如果股价列表长度小于等于1,无法进行交易,返回0 if n <= 1: return 0 # 初始化最大利润为0,最低股价为第一天的股价 max_profit = 0 min_price = prices[0] # 遍历股价列表 for price in prices: # 更新最低股价为当前股价和最低股价的较小值 min_price = min(min_price, price) # 计算当前卖出时的利润(当前股价减去最低股价) current_profit = price - min_price # 更新最大利润为当前利润和最大利润的较大值 max_profit = max(max_profit, current_profit) # 返回最终的最大利润 return max_profit
标签:买卖,cur,self,leedcode,maxProfit,最佳时机,prices,return From: https://www.cnblogs.com/yyyjw/p/18032766