File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments