Skip to content

Commit 371fe96

Browse files
committed
better solution of Best Time To Buy And Sell Stock II
1 parent 416c5d9 commit 371fe96

File tree

1 file changed

+31
-1
lines changed
  • algorithms/BestTimeToBuyAndSellStockII

1 file changed

+31
-1
lines changed
Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,32 @@
11
# Best Time To Buy And Sell Stock
2-
This problem is easy to solve
2+
This problem is easy to solve by Greedy Algorithm, like below:
3+
```python
4+
class Solution(object):
5+
def maxProfit(self, prices):
6+
"""
7+
:type prices: List[int]
8+
:rtype: int
9+
"""
10+
if len(prices) == 0:
11+
return 0
12+
13+
max_profit = 0
14+
holder = prices[0]
15+
max_price = prices[0]
16+
17+
for i in xrange(1, len(prices)):
18+
price = prices[i]
19+
20+
if price > max_price:
21+
max_price = price
22+
elif max_price > price:
23+
if max_price > holder:
24+
max_profit += max_price - holder
25+
holder = price
26+
max_price = price
27+
28+
if max_price > holder:
29+
max_profit += max_price - holder
30+
31+
return max_profit
32+
```

0 commit comments

Comments
 (0)