- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStockIII.py
More file actions
Latest commit
39 lines (32 loc) · 1.26 KB
/
Copy pathStockIII.py
File metadata and controls
39 lines (32 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
classSolution:
# @param prices, a list of integer
# @return an integer
defmaxProfit(self, prices):
# Solve problem going backwards.
ifnotprices:
return0
tail_max_profit= [0for_inrange(len(prices))]
max_from_tail=prices[-1]
max_profit_from_tail=0
foriinrange(len(prices) -2, -1, -1):
cost=prices[i]
max_from_tail=max(max_from_tail, cost)
max_profit_from_tail=max(max_profit_from_tail, max_from_tail-cost)
tail_max_profit[i] =max_profit_from_tail
print'cost %d, max from tail %d, max profit from tail %d'%(cost,max_from_tail,max_profit_from_tail)
printtail_max_profit
# print tail_max_profit
# Solve problem going forward.
min_from_head=prices[0]
max_profit_from_head=0
# Max profit from two transactions.
max_profit_2=max_profit_from_head+tail_max_profit[0]
foriinrange(1, len(prices) -1):
cost=prices[i]
min_from_head=min(min_from_head, cost)
max_profit_from_head=max(max_profit_from_head, cost-min_from_head)
max_profit_2=max(
max_profit_2, max_profit_from_head+tail_max_profit[i])
returnmax_profit_2
# print Solution().maxProfit([])
printSolution().maxProfit([2,1,2,0,1])