Skip to content

Commit 3d142b3

Browse files
committed
买卖股票的最佳时机 III
1 parent f2ac985 commit 3d142b3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param prices: Given an integer array
6+
@return: Maximum profit
7+
"""
8+
def maxProfit(self, prices):
9+
# write your code here
10+
ret = 0
11+
if prices:
12+
max_profit_1, max_profit_2 = 0, 0
13+
min_price, max_price = prices[0], prices[-1]
14+
profits = [0] * len(prices)
15+
# 顺序找一次
16+
for i in xrange(1, len(prices)):
17+
profit = prices[i] - min_price
18+
if profit < 0:
19+
min_price = prices[i]
20+
else:
21+
if profit > max_profit_1:
22+
max_profit_1 = profit
23+
profits[i] = max_profit_1 # 记录当前位置最大利润
24+
# 从后往前再找一次,利用第一次profits的结果。
25+
for i in xrange(len(prices) -2 , -1, -1):
26+
profit = max_price - prices[i]
27+
if profit < 0:
28+
max_price = prices[i]
29+
else:
30+
if profit > max_profit_2:
31+
max_profit_2 = profit
32+
if (max_profit_2 + profits[i]) > ret: # 有先买后卖的限制
33+
ret = max_profit_2 + profits[i]
34+
return ret

0 commit comments

Comments
 (0)