[LeetCode]Best Time to Buy and Sell Stock with Transaction Fee

题目描述:

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

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:

Note:

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

题目大意:

给定一组股票价格prices,股票印花税fee(卖出股票时征收)。

求一组买入卖出序列,使得总收益最大。

解题思路:

栈(Stack)

栈中保存交易序列[buy, sell],当sell为0时表示还没有卖出

遍历prices,记当前价格为price:

若栈顶交易sell为0,并且price <= buy,则将栈顶buy替换为price

否则,若price >= max(栈顶sell,栈顶buy + fee),则替换栈顶sell为price

否则,将[price, 0]压栈

当栈元素>1,并且合并栈顶的两组交易可以获得更大收益时,对栈顶的两个交易进行合并

Python代码:

class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        ts = [[50000, 0]]
        for price in prices:
            if not ts[-1][1] and price <= ts[-1][0]:
                ts[-1][0] = price
            elif price >= max(ts[-1][1], ts[-1][0] + fee):
                ts[-1][1] = price
            elif ts[-1][1]:
                ts.append([price, 0])
            while len(ts) > 1 and ts[-2][1] < ts[-1][0] + fee:
                ts[-1][1] = max(ts.pop()[1], ts[-1][1])
        return sum(t[1] - t[0] - fee for t in ts if t[1] - t[0] > fee)

 

本文链接:http://bookshadow.com/weblog/2017/10/22/leetcode-best-time-to-buy-and-sell-stock-with-transaction-fee/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论