Best time to buy and sell stock II

Question

Say you have an array 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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Thoughts

这一题变为了可以完成尽量多的交易次数

也就是说每一个上升的利润都可以捕捉到,下降的就忽略,为0不记录到profit里面 所以可以每个相邻的天数都可以交易,只要后一天比前一天高,就可以记录到利润里

Solution

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        maxProfit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                maxProfit += prices[i] - prices[i-1]
        return maxProfit