122. Best Time to Buy and Sell Stock II
作者:互联网
这道题里面可以买卖股票多次。
这里我加入了sell price。
基本上就是有这个特性:如果看到价格比卖出价格低,就应该换手,这样肯定比不换手得到的利润要高。
Greedy算法就可以解决这个问题。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# Initially looks like that this is a DP problem because the past results need to be saved
# We don't know which case is better, 1,3,2,5 or 1-3,2-5, or 1-5
# BUT we can always get a cheaper buying price than the selling price, it's always good to switch hands.
# This is greedy algorithm.
if not prices: return 0
max_profit = max_profit_round = 0
buying_price = prices[0]
selling_price = 0
for price in prices:
#print("price: %d, buying price: %d, selling price: %d" % (price, buying_price, selling_price))
if price < buying_price:
buying_price = price
#print("updating buying price to %d" % price)
elif price > buying_price:
if price-buying_price > max_profit_round:
selling_price = price
max_profit_round = price-buying_price
#print("Updating selling price to %d" % price)
if price < selling_price: # 这里,一定是IF,不是elif,算是比前一题附加一点。
max_profit += max_profit_round
max_profit_round = 0
buying_price = price
#print("Refresh my stock price to %d, profit to %d" % (price, max_profit))
max_profit += max_profit_round
return max_profit
标签:Sell,Buy,profit,max,price,II,selling,round,buying 来源: https://blog.csdn.net/SpanningWings/article/details/101146168