Skip to content

Commit 6429124

Browse files
committed
2020-07-09
1 parent 6a25c4f commit 6429124

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution(object):
2+
def maxProfit(self, prices):
3+
"""
4+
:type prices: List[int]
5+
:rtype: int
6+
"""
7+
#dp[i][k][1/0]表示第i天还可以交易k次手上持有或没持有股票的状态
8+
#对于第二题,k = 2
9+
#dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + price[i])
10+
#dp[i][k][1] = max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - price[i])
11+
#当k = 0时, dp[i][0][1/0] = 0
12+
dp = [[0 for _ in range(2)] for _ in range(len(prices))]
13+
14+
for i in range(len(prices)):
15+
if i == 0:
16+
dp[i][0] = 0
17+
dp[i][1] = -prices[i]
18+
else:
19+
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])
20+
dp[i][1] = max(dp[i - 1][1], dp[i - 2][0] - prices[i])
21+
22+
# print dp
23+
return dp[len(prices) - 1][0] if prices else 0

0 commit comments

Comments
 (0)