Daily Leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
Medium
问题描述:
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:
1 | Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 |
Note:
0 < prices.length <= 50000
.
0 < prices[i] < 50000
.
0 <= fee < 50000
.
题目分析:
给定数组prices
,第i-th
元素表示在第i
天的股票价格,每一手股票,需要收取的手续费为fee
,同时最多持有一只股票,我们需要寻找最好的买入卖出策略,从而得到最大利润。
这一题同样可以使用动态规划思想来解决,我们需要两个状态,一个是买状态,一个是卖状态。买状态其实保存的是当前最小的购买花费,卖状态保存的是直到目前最大的收益。买入卖出操作均有前一天的买卖状态决定,当收益
“为大”,就执行卖出操作。
以题目所给示例为例:
1 | buy[0] = -fee - prices[0] = -3 #第一天买入股票的花费 |
代码:
1 | class Solution(object): |