Description:
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).
Solution:
Time Complexity : O(n)
Space Complexity: O(1)
var maxProfit = function(prices, fee) {
// The max profit we could make
let profit = 0;
// Total profit if we bought at the current price
let hold = -prices[0];
// Loop through all the days
for (let i = 1; i < prices.length; i++) {
// Check if it would be more profitable to hold or sell
profit = Math.max(profit, hold + prices[i] - fee);
// Check if it would be more profitable to hold or buy
hold = Math.max(hold, profit - prices[i]);
}
return profit;
};
Top comments (0)