最开始的思路是在上一题(买卖股票的最佳时机 I) 的基础上,从卖出的那天(下标为i)之后开始算,也就是list中下标i+1开始。但后来发现这样是不对的,上一题要求计算最大收益,本题是只要有钱赚就卖掉。所以代码如下:
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
i = 0
profit = 0
while i < len(prices)-1:
if prices[i+1] > prices[i]:
profit += prices[i+1] - prices[i]
i += 1
return profit