122. Best Time to Buy and Sell Stock II

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

买股票问题,可以任意次数买卖,但是买的时候手上必须没股票了。做法很简单,只要判断今天的股价是否大于昨天的,大于的话就加上收益,因为你总可以昨天买今天卖然后今天买明天又卖。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        ans = 0
        for i in range(1, len(prices), 1):
            if prices[i] > prices[i - 1]:
                ans += prices[i] - prices[i - 1]
        return ans
        
原文地址:https://www.cnblogs.com/whatyouthink/p/13226801.html