# Best Time To Buy And Sell Stock With Transaction Fee Problem

## Description

LeetCode Problem 714.

You are given an 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.

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:

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

Example 2:

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

Constraints:

• 1 <= prices.length <= 5 * 10^4
• 1 <= prices[i] < 5 * 10^4
• 0 <= fee < 5 * 10^4

## Sample C++ Code

``````1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
// s0 = profit having no stock
// s1 = profit having 1 stock
int s0 = 0, s1 = INT_MIN;
for (int p : prices) {
int tmp = s0;
// update s0 by selling the stock from s1, so s0 = max(s0, s1+p);
// update s1 by buying the stock from s0, so s1 = max(s1, s0-p-fee);
s0 = max(s0, s1 + p);
s1 = max(s1, tmp - p - fee);
}
return s0;
}
};
``````