[一起来刷leetcode吧][15]--No.714 Best Time to Buy and Sell Stock with Transaction Fee

本文介绍了一种解决LeetCode第714题“含手续费的最佳股票买卖时机”问题的方法。通过动态规划来确定最大利润,考虑了交易费用的影响,并提供了一个Python实现方案。
这篇文章是程序自动发表的,详情可以见 这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">

这是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: 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.   思路 动态规划,弄清楚,f(n),与f(n 1)的关系,确定转移方程,以及当再次加入一组时是否可以多于两次的fee,代码29,30行就是处理这点   

show me the code

class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        n = len(prices)
        if n<2:return 0
        li = []
        if prices[1]-prices[0]>fee:
            li.append([0,1])
            idx = -1
        else:
            if (prices[0]>prices[1]):idx = 1
            else:idx = 0
        for i in range(2,n):
            if not li:
                if  prices[i]-prices[idx]>fee:li.append([idx,i])
                elif prices[i]<prices[idx]:idx = i
            else:
                last = li[-1]
                if last[1] == i-1 :
                    if prices[i]>prices[last[1]]: 
                        last[1] = i
                    else:idx = i
                else:
                    if prices[i]>prices[idx] fee:
                        if prices[last[1]]-prices[idx]<fee:
                                last[1] = i
                        else:li.append([idx,i])
                    elif prices[i]>prices[last[1]]: last[1]=i
                    elif prices[i]<prices[idx]:idx=i
        s=[prices[i[1]]-prices[i[0]]-fee for i in li]
        return sum(s)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值