剑指offer面试题63. 股票的最大利润(动态规划)

题目描述

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
剑指offer面试题63. 股票的最大利润(动态规划)_第1张图片

思路

详见链接

代码

class Solution:
	def maxProfit(self, prices:List[int])->int:
		cost, profit = float("inf"), 0
		for price in prices:
			cost = min(cost, price)
			profit = max(profit, price - cost)
		return profit

复杂度

时间复杂度 O(N): 其中 NN 为 prices列表长度,动态规划需遍历 prices 。
空间复杂度 O(1) : 变量 cost 和 profit 使用常数大小的额外空间。

你可能感兴趣的:(剑指offer)