712377. Buy Stock with Transaction Fee
Buy Stock with Transaction Fee
Summary
You are given an array prices representing stock prices over time, where each price is a non-negative integer. You can buy and sell stocks, but for each transaction, you need to pay a fee. Your goal is to maximize your profit by determining the optimal sequence of buy and sell transactions.
The problem involves arrays and algorithms, focusing on finding the maximum possible profit considering the transaction fee.
Detailed Explanation
To solve this problem, we will use dynamic programming to find the maximum profit. We will initialize an array dp with the same length as prices, where dp[i] represents the maximum profit that can be achieved by the end of day i.
Here's a step-by-step breakdown:
- Initialize
max_profit = 0andprev_min_price = prices[0]. - Iterate through the array
prices:- For each day
i, calculate the profitprofit = prices[i] - prev_min_price. If this is positive, add the fee to the profit (profit -= fee). - Update
max_profitif the current profit is greater. - Update
prev_min_priceas the minimum price seen so far.
- For each day
- Return
max_profitas the maximum possible profit.
Time complexity: O(n), where n is the length of the array prices.
Space complexity: O(1), since we only use a constant amount of space to store the variables.
Optimized Solutions
Java
public int maxProfit(int[] prices, int fee) {
int max_profit = 0;
int prev_min_price = prices[0];
for (int i = 1; i < prices.length; i++) {
int profit = prices[i] - prev_min_price;
if (profit > 0) {
profit -= fee;
}
max_profit = Math.max(max_profit, profit);
prev_min_price = Math.min(prev_min_price, prices[i]);
}
return max_profit;
}