LeetCode Solutions

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

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int maxProfit(vector<int>& prices, int fee) {
    int sell = 0;
    int hold = INT_MIN;

    for (const int price : prices) {
      sell = max(sell, hold + price);
      hold = max(hold, sell - price - fee);
    }

    return sell;
  }
};
			

class Solution {
  public int maxProfit(int[] prices, int fee) {
    int sell = 0;
    int hold = Integer.MIN_VALUE;

    for (final int price : prices) {
      sell = Math.max(sell, hold + price);
      hold = Math.max(hold, sell - price - fee);
    }

    return sell;
  }
}
			

class Solution:
  def maxProfit(self, prices: List[int], fee: int) -> int:
    sell = 0
    hold = -math.inf

    for price in prices:
      sell = max(sell, hold + price)
      hold = max(hold, sell - price - fee)

    return sell