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)

本文介绍了一种解决LeetCode第714题“含手续费的最佳股票买卖时机”问题的方法。通过动态规划来确定最大利润,考虑了交易费用的影响,并提供了一个Python实现方案。
285

被折叠的 条评论
为什么被折叠?



