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).
new solution update 2022.03.10
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intmaxProfit(vector<int>& prices, int fee){ int profit = 0, n = prices.size(), sellMax = 0, sell; for(int i = n - 1; i >= 0; i--) { sell = sellMax; sellMax = max(sellMax, profit + prices[i] - fee); profit = max(profit, sell - prices[i]); } return profit; } };
new solution update 2022.02.08
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { int dp[50001][2]; intdfs(vector<int>& prices, int i, int& fee, bool hasStock){ if(i >= prices.size()) return0; if(dp[i][hasStock] != -1) return dp[i][hasStock]; if(hasStock) { dp[i][hasStock] = max(dfs(prices, i + 1, fee, hasStock), prices[i] + dfs(prices, i + 1, fee, !hasStock)); } else { dp[i][hasStock] = max(dfs(prices, i + 1, fee, hasStock), dfs(prices, i + 1, fee, !hasStock) - prices[i] - fee); } return dp[i][hasStock]; } public: intmaxProfit(vector<int>& prices, int fee){ memset(dp, -1, sizeof(dp)); returndfs(prices, 0, fee, false); } };