给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
方案一:利润累加
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices or len(prices) < 2:
return 0
profit = 0
for i in range(len(prices) - 1):
if prices[i + 1] > prices[i]:
profit += prices[i + 1] - prices[i]
return profit
方案二:思路与方案一一样,更方便理解。 只要后一天的价格高便卖出,同时买进,把每次的利润加起来便是总利润。
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices or len(prices) < 2:
return 0
profit, begin_price = 0, prices[0]
for p in prices:
if p > begin_price:
profit += p - begin_price
begin_price = p
return profit