Q121. Best Time to Buy and Sell Stock https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
给定一串数组代表股票价格,确定买入时间和卖出时间使得收益最大。注意:只能交易一次!
idea1:
暴力解法:循环遍历两次,针对每个元素都计算后面剩余元素与之的差值,并记录最大差值即为最大收益。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices==[]:
return 0
max_profit = 0
buy = 0
sell = 0
for i in range(len(prices)):
for j in range(i+1,len(prices),1):
profit = prices[j]-prices[i]
if profit > max_profit:
buy = i
sell = j
max_profit = profit
return prices[sell]-prices[buy]
时间复杂度为O(N2),超时了。
idea2:
针对每一个元素,找到它后面剩余元素的最大值并作差,迭代记录最大差值。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices==[]:
return 0
max_profit = 0
for i in range(len(prices)-1):
buy = prices[i]
sell = max(prices[i+1:])
profit = sell-buy
if profit > max_profit:
max_profit = profit
return max_profit
仍然很耗时。
discussion解决方案:
一次处理。一边找最小值一边找最大收益。用两个变量min_price和max_profit,分别记录最小的买入价格和最大收益。依次遍历数组元素,当出现比min_price小的元素时,记录该元素为min_price,然后寻找针对min_price的最大收益。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices == []:
return 0
min_price = prices[0]
max_profit = 0
for i in range(1,len(prices)):
if prices[i] < min_price:
min_price = prices[i]
elif (prices[i]-min_price) > max_profit:
max_profit = prices[i]-min_price
return max_profit
思路很巧妙,学习了
Q122. Best Time to Buy and Sell Stock II https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
该问题是上一个问题的升级版,区别是可以多次交易,并且可以在同一天买入和卖出。
该问题的solution里面分析的很透彻
情况1:价格波动,有高有低。A+B > C
情况2:价格连续增长。A+B+C = D
所有向上的走势都进行交易。即遍历每个元素prices[i],若prices[i+1]>prices[i],就卖出。将收益累加得到最大收益。这个题的核心是要弄清楚上面两个图中的价格规律。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in range(1, len(prices)):
if prices[i] >= prices[i-1]:
profit += prices[i]-prices[i-1]
return profit