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

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/

> 内容描述

```
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.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

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.
Note:

0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

直接看的solution


1. 如果今天过后我手上有股票：
  - 要么是我昨天有股票今天没卖
  - 要么是我昨天没有股票，但是今天买了
  - own = max(own, notown - prices[i])
2. 如果今天过后我手上没有股票：
  - 要么是我昨天就没有股票今天也没有买
  - 要么是我昨天手上有股票，但是今天卖了
  - notown = max(notown, own + prices[i] - fee)
  
  
beats 70.38%
  
```python
class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        notown, own = 0, -prices[0] # 第一天就有股票说明我第一天买了股票，因此profit为 -prices[0]
        for i in range(1, len(prices)):
            notown = max(notown, own + prices[i] - fee)
            own = max(own, notown - prices[i])
        return notown
```







































