给定一个数组,它的第?i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
max_value
记录最大利润。price_buy
和在其之后的最大价格,即卖出价格sell_price
作差:price_sell - price_buy
,得到买入价格price_buy
的最大利润max_i
。max_value
和当天买入价格price_buy
的最大利润max_i
较大值为max_value
max_value
为结果。class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_value = 0
for i in range(len(prices)):
price_buy = prices[i]
price_sell = max(prices[i:])
max_i = price_sell - price_buy
max_value = max(max_i, max_value)
return max_value
min_value
,最大利润max_profit
。price
:
min_value
与当前价格price
比较取较小,更新最低价格min_value
。price
和最低价格min_value
的差与最大利润max_profit
取较大,更新最大利润max_profit
。max_profit
为结果。class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_value = float("inf")
max_profit = 0
for price in prices:
min_value = min(price, min_value)
max_profit = max(max_profit, price - min_value)
return max_profit
Leetcode daily 20/03/09 买卖股票的最佳时机 笔记
原文:https://www.cnblogs.com/Chunngai/p/12456285.html