频道栏目
首页 > 考试 > 其他 > 正文

Best Time to Buy and Sell Stock with Transaction Fee

2018-04-11 02:07:13      个评论    来源:mbinary  
收藏   我要投稿

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[last[1]]: 
                        last[1] = i
                    else:idx = i
                else:
                    if prices[i]>prices[idx] fee:
                        if prices[last[1]]-prices[idx]prices[last[1]]: last[1]=i
                    elif prices[i]
                            
  
上一篇:Trie( Prefix Tree)
下一篇:最大和 最大子矩阵模板题
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站