Best Time to Buy and Sell Stock with Transaction Fee

problem [https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ 714. Best Time to Buy and Sell Stock with Transaction Fee].

Problem description
You are given an array  where   is the price of a given stock on the   day, and an integer   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).


 * Example 1
 * Input: prices = [1,3,2,8,4,9], fee = 2
 * Output: 8
 * Explanation: The maximum profit can be achieved by:
 * Buying at prices[0] = 1
 * Selling at prices[3] = 8
 * Buying at prices[4] = 4
 * Selling at prices[5] = 9
 * The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.


 * Example 2
 * Input: prices = [1,3,7,5,10,3], fee = 3
 * Output: 6


 * Constraints

Problem analysis
This problem is similar to Best Time to Buy and Sell Stock II, except that for each transaction there will be a transaction fee subtracted from the profit from the transaction.

We can still use two variables  and   to keep track of the maximum possible balance and profit at hand after each day. But, since we now have the transaction fee, the transition equations must be slightly modified to account for the transaction fee.

We first initialize  and.

Then for days i = 1, 2, …, n-1, we update and  :
 * : the maximum balance at hand if we do not purchase a new stock on day i.
 * : the maximum balance at hand if we do purchase a new stock on day i.
 * : the maximum profit we can make on day i if we do not sell the stock on day i.
 * : the maximum profit we can make on day i if we do sell the stock on day i.
 * : the maximum profit we can make on day i if we do not sell the stock on day i.
 * : the maximum profit we can make on day i if we do sell the stock on day i.

Finally the  will be the result.

Working example

 * Input: prices = [5, 1, 2, 3, 7, 2, 5, 1, 3], fee = 2
 * Return: 5
 * Buy on day 1 → sell on day 4 (profit: 4)
 * Buy on day 5 → sell on day 6 (profit: 1)

Complexity analysis

 * Time complexity
 * Since we have iterated through all the days, and the computation for each day is constant, the total time complexity is O(n), where n is the total number of days.


 * Space complexity
 * Since we only used two variables  and   and did not create additional data structures, the total space complexity is O(1).