Best Time to Buy and Sell Stock with Transaction Fee - Medium - L - Star
Published:
Question
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Approach
- Variable iteration
- https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323
Solution
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
if (n<2) {
return 0;
}
int buy0,buy1,sell0,sell1;
buy0 = -prices[0]-fee;
sell0 = 0;
for(int i=1;i<n;i++) {
buy0 = max(buy0, sell0-prices[i]-fee);
sell0 = max(sell0, buy0 + prices[i]);
}
return sell0;
}
};