121.买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
解
- 双指针 i j
- i 指向当前遍历过的价格中最小价格的索引
- j 指向当前遍历价格的索引
- i必须小于j
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if prices == []:
return 0
n = len(prices)
if n == 1:
return 0
i = 0
j = 1
result = 0
while j < n:
if prices[i] >= prices[j]:
i = j
else:
result = max(result, prices[j] - prices[i])
j += 1
return result