Analysis:
we use
sells
to depict whether the maximum profit when selling stock at price[i]
andbuys
to depict the maximum profit when buying at prices[i]
so we can getsells[i] = max(sells[i-1], buys[i-1]+prices[i])
buys[i] = max(buys[i-1], sells[i-2]-prices[i])
Time Complexity:
- O(n)
Space Complexity:
- O(n)
Code
1 | class Solution(object): |