Best Time to Buy and Sell Stock II

Question

Say you have an array for which the $$i_{th}$$ 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).

Tag

  • Array
  • Greedy

Thought

Since we can sell the stock at one day and then buy the stock at the same day, we can simply assume we sell the stock every time as long as the price is higher than that when we bought it. The result will be the same. Then, we can simply use the Greedy algorithm to solve the problem.

Code

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        result = 0
        n = len(prices)
        for i in range(n - 1):
            if prices[i] < prices[i + 1]:
                result += prices[i + 1] - prices[i]
        return result

results matching ""

    No results matching ""