Skip to content

Commit 282d670

Browse files
committed
Dynamic Programming solution of Best Time To Buy And Sell Stock II
1 parent d9c85c4 commit 282d670

File tree

1 file changed

+21
-0
lines changed
  • algorithms/BestTimeToBuyAndSellStockII

1 file changed

+21
-0
lines changed

algorithms/BestTimeToBuyAndSellStockII/README.md

+21
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,25 @@ class Solution(object):
4747
max_profit += prices[i] - prices[i - 1]
4848

4949
return max_profit
50+
```
51+
or use Dynamic Programming like below:
52+
```python
53+
class Solution(object):
54+
def maxProfit(self, prices):
55+
"""
56+
:type prices: List[int]
57+
:rtype: int
58+
"""
59+
if len(prices) == 0:
60+
return 0
61+
# profit of not hold stock in i
62+
not_holder = 0
63+
# profit of hold stock in i, of course it's -prices[0] when i = 0
64+
holder = -prices[0]
65+
66+
for i in xrange(1, len(prices)):
67+
not_holder = max(not_holder, prices[i] + holder)
68+
holder = max(holder, not_holder - prices[i])
69+
70+
return max(holder, not_holder)
5071
```

0 commit comments

Comments
 (0)