> For the complete documentation index, see [llms.txt](https://ucan.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ucan.gitbook.io/notes/dynamic-programming/714.-best-time-to-buy-and-sell-stock-with-transaction-fee.md).

# 714. Best Time to Buy and Sell Stock with Transaction Fee

[Your are given an array of integers `prices`, for which the `i`-th element is the price of a given stock on day `i`; and a non-negative integer `fee` representing a transaction fee.](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)

```java
class Solution {
    public int maxProfit(int[] prices, int fee) {
        // sold[i] = Math.max(sold[i-1], hold[i-1]+prices[i]-2);
        // hold[i] = Math.max(hold[i-1], sold[i-1]-prices[i]);
        // base sold[0] = 0, hold[0]=-prices[0];
        
        if (prices.length<1) return 0;
        int sold=0, hold=-prices[0];
        for (int i=1; i<prices.length;i++){
            int temp = sold;
            sold = Math.max(sold, hold+prices[i]-fee);
            hold = Math.max(hold, temp-prices[i]);
        }
        
        return Math.max(sold, hold);
    }
}
```
