买卖股票的最佳时机

买卖股票的最佳时机

1、题目

图1

2、题解

动态规划

  • 更新前\(i\)天的最低价格,即最低买入成本\(cost\)
  • 更新前\(i\)天的最高利润\(profit\),即选择前\(i-1\)天最高利润\(profit\)和第\(i\)天卖出的最高利润\(price-cost\)中的最大值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def maxProfit(self, prices: List[int]) -> int:
cost = prices[0]
days = len(prices)
money = 0

for price in prices:
if cost >= price:
cost = price

if money<=price-cost:
money = price-cost

return money

买卖股票的最佳时机
http://example.com/2024/04/14/买卖股票的最佳时机/
作者
Z Z
发布于
2024年4月14日
许可协议