Catalogue
121. Best Time to Buy and Sell Stock
- Complete at most one transaction
- We can get max profit when we buy on the lowest price and sell on the highest price!
- we need to find $max(prices[j] - prices[i])$, for every i and j such that j > ij>i.
1
2
3
4
5
6
7
8
9
10
11class Solution(object):
def maxProfit(self, prices):
if not prices:
return 0
minp = prices[0]
maxProfit = 0
for i in xrange(1, len(prices)):
minp = min(minp, prices[i])
maxProfit = max(maxProfit, prices[i] - minp)
return maxProfit
122. Best Time to Buy and Sell Stock II
- Complete as many transactions as you like
- Greedy Algorithms
1 | class Solution(object): |
122. Best Time to Buy and Sell Stock III
- Complete at most two transactions
1 | class Solution(object): |
188. Best Time to Buy and Sell Stock IV
- Complete at most k transactions
- Watch Out: when k > n/2, you can use greedy algorithm from II
1 | class Solution: |
- Why do we need local and global two dp states?
1 | class Solution: |
309. Best Time to Buy and Sell Stock with Cooldown
- The natural states for this problem is the 3 possible transactions : buy, sell, rest. Here rest means no transaction on that day (aka cooldown).
1 | class Solution: |
1 | class Solution: |
714. Best Time to Buy and Sell Stock with Transaction Fee
1 | class Solution: |
Summary
States Definition
- Then the transaction sequences can end with any of these three states.
For each of them we make an array, buy[n], sell[n] and rest[n].
- buy[i] means before day i what is the maxProfit for any sequence end with buy.
- sell[i] means before day i what is the maxProfit for any sequence end with sell.
- rest[i] means before day i what is the maxProfit for any sequence end with rest.
- Hold and Unhold
- hold[i] means before day i what is the maxProfit for any sequence end with holding stock.
- unhold[i] means before day i what is the matProfit for any sequence end with unholding stock.
Induction Rule
TODO
Space Improving
TODO