Buy and sell once
Leetcode 121. Best Time to Buy and Sell Stock
1 | Say you have an array for which the ith element is the price of a given stock on day i. |
Solution
The max profit of current state only relevent to the previous minimium price. So we can use one variable to record the previous minimium price and update the current max profit.
The state transfer function is:
1 | class Solution: |
Buy and sell multiple times
Leetocde 122 Best Time to Buy and Sell Stock II
1 | Say you have an array for which the ith element is the price of a given stock on day i. |
Solution
- Mathemetical View

If we analyze the graph, we notice that the points of interest are the consecutive valleys and peaks. For example, in the above case, if we skip $peak_i$ and $vally_j$, trying to obtain more profit by considering points with more difference in heights, the net profit obtained will always be lesser than the one obtained by including them, Since:
Therefore, we can find all the preak and valley pairs and calculate the total Profit:
1 | class Solution: |
- Dynamic Programming
At the end of the $i_{th}$ day, we maintain cash
, the maximum profit we could have if we did not have a share of stock, and hold, the maximum profit we could have if we owned a share of stock.
The intution is the state of today is only relevent to the yesterday. The State of yesterday can be expressed as :
Therefore , we can use two variables cash
, hold
to represent the above two states. The state transfer functions are:
- keep the same as day i-1, or sell from hold status at day i-1
- keep the same as day i-1, or buy from cash status at day i-1
1 | class Solution: |
Leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee
1 | Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee. |
Solution
- Dynamic Programming
See explanation above.
1 | class Solution: |