https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
There could be two possible states after visiting prices[i-1]:
1. hold: there is 1 share of stock at hand. The total cash is named hold.
2. sold: there is 0 share of stock at hand. The total cash is named sold.
After visiting prices[i], the states are
1. hold = max(hold at i-1, sold at i-1 and buy 1 share at i)
2. sold = max(sold at i-1, hold at i-1 and sell 1 share at i)
int maxProfit(vector<int>& prices, int fee) {
// at i=0, the total cash at hand could be sold or hold:
int sold = 0, hold = -prices[0];
for(int i=1; i<prices.size(); i++) {
int h = max(hold, sold - prices[i]);
int s = max(sold, hold + prices[i] - fee);
sold = s;
hold = h;
}
return sold;
}
or, check local min and max
int maxProfit(vector<int>& prices, int fee) {
prices.push_back(-50000);
int hold = -prices[0], cash = 0;
for(int i=1; i<prices.size()-1; i++) {
if(prices[i]<=prices[i-1] && prices[i]<prices[i+1]) {
// local minimum
hold = max(hold, cash - prices[i]);
}
else if(prices[i]>=prices[i-1] && prices[i]>prices[i+1]) {
// local maximum
cash = max(cash, hold + prices[i] -fee);
}
}
return cash;
}
No comments:
Post a Comment