Skip to content

Commit c1061fd

Browse files
committed
Create 40. 买卖股票的最佳时机.md
1 parent 20ebbbf commit c1061fd

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

40. 买卖股票的最佳时机.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
***给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。***
2+
3+
```
4+
输入:[7,1,5,3,6,4]
5+
输出:5
6+
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
7+
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
8+
```
9+
10+
```
11+
class Solution:
12+
def maxProfit(self, prices: List[int]) -> int:
13+
#动态规划,dp[i]表示在第i天之前的最低买入价,不包括第i天。当i=0时特殊处理
14+
n = len(prices)
15+
dp = [0]*n
16+
dp[0] = prices[0]
17+
18+
for i in range(1, n):
19+
dp[i] = min(dp[i-1], prices[i-1])
20+
profits = [a-b for a, b in zip(prices, dp)]
21+
return max(profits)
22+
```

0 commit comments

Comments
 (0)