力扣数组基础题(2)买卖股票的最佳时机

题目

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

自解

暴力解法——题解说超时了

有思路但不多,遍历数组不怎么费脑子。

1
2
3
4
5
6
7
def maxProfit(self, prices: List[int]) -> int:
    maxprofit = 0
    minprice = 1e9
    for i in range(len(prices)):
        for j in range(i+1,len(prices)):
            maxprofit=max(prices[j]-prices[i],maxprofit)
    return maxprofit

题解

一次遍历

1
2
3
4
5
6
7
def maxProfit(self, prices: List[int]) -> int:
	maxprofit = 0
	minprice = float('inf')
	for i in range(len(prices)):
		maxprofit = max(prices[i] - minprice, maxprofit)
		minprice = min(prices[i], minprice)
	return maxprofit

对于有顺序要求的情况,枚举右,查找左一般比较容易。