题目:Best Time to Buy and Sell the Stocks
思路:(啊这道题吧 我觉得一直想不清楚的我自己是个傻逼)意思是,把一个stocks在最低价买进最高价卖出(一次性),总是会少于在期间一直买入卖出之和的,说的不太清楚但是意思是下面这个意思:
这个是来自题目本身的solution 意思就是 C < A+B. (这个怎么能都想不到呢。)所以如果允许买卖多次,那么最大的收益就是升就卖(prices[i] > prices[i+1])降就买进
其实solution里面的2和3的思路都是一样,只是一个考虑到了升到最高的时候卖出,直接计算最大收益,另一个则直接加上罢了。
比较简洁的一种解决方法:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
i = 0
max_profit = 0
while i < len(prices) - 1:
if prices[i] < prices[i+1]:
max_profit += prices[i+1] - prices[i]
i += 1
return max_profit