Best Time to Buy and Sell Stock with Transaction Fee
You are given an integer 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 (you must sell the stock before you buy again).
- The transaction fee is charged exactly once per completed transaction. It is deducted when the share is sold, so a transaction's profit is the sell price minus the buy price minus the fee.
- A transaction must buy before it sells, and a new transaction may start only after the previous share is sold.
Examples
Input: [[1,3,2,8,4,9],2]
Output: 8
Input: [[],0]
Output: 0
Hints
Identify that this problem can be solved using dynamic programming by tracking two states: holding a stock or not holding a stock.
Define `dp[i][0]` as the maximum profit on day `i` without holding a stock, and `dp[i][1]` as the maximum profit on day `i` holding a stock. Derive the recurrence relations:
`dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i] - fee)`
Best Time to Buy and Sell Stock with Transaction Fee
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `i`th day, and an integer `fee` representing a transaction fee.