Skip to content

Commit d9c85c4

Browse files
committed
Dynamic Programming solution of Best Time To Buy And Sell Stock With Transaction Fee
1 parent f7c5630 commit d9c85c4

File tree

1 file changed

+23
-1
lines changed
  • algorithms/BestTimeToBuyAndSellStockWithTransactionFee

1 file changed

+23
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,24 @@
11
# Best Time To Buy And Sell Stock With Transaction Fee
2-
We can solve this problem by Greedy Algorithm
2+
We can solve this problem by Greedy Algorithm, or use Dynamic Programming like below:
3+
```python
4+
class Solution(object):
5+
def maxProfit(self, prices, fee):
6+
"""
7+
:type prices: List[int]
8+
:type fee: int
9+
:rtype: int
10+
"""
11+
if len(prices) == 0:
12+
return 0
13+
# profit of not hold stock in i
14+
not_holder = 0
15+
# profit of hold stock in i, of course it's -prices[0] when i = 0
16+
holder = -prices[0]
17+
18+
for i in xrange(1, len(prices)):
19+
not_holder = max(not_holder, prices[i] + holder - fee)
20+
holder = max(holder, not_holder - prices[i])
21+
22+
return max(holder, not_holder)
23+
24+
```

0 commit comments

Comments
 (0)