【LeetCode OJ】Best Time to Buy and Sell Stock II

Posted on 2014-05-06 22:58  卢泽尔  阅读(215)  评论(0)    收藏  举报

Problem Link:

http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

We solve this problem using Greedy Algorithm, which only scan the prices list once. The worst-case running time is O(n).

According to the problem description, we know that the trasaction operations must be:

      buy, sell, buy, sell, ..., buy, sell

For each day, we have two status, holding stocks or not, we have no stocks in day 0.

Then for each day i, we decide to buy or sell according to the prices of the following day:

  1. if we have no stock: we buy stock if prices[i] < prices[i+1]; otherwise, we do nothing.
  2. if we have stock: we sell stock if prices[i] > prices[i+1]; otherwise, we do nothing.

Note that we need to sell the stock in the last day if we have stock after scanning prices[0:n-1].

The python code is as follows.

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        """
        We solve this problem using Greedy algorithm, since you can only buy one or sell one each day.
        For each day, we have two possible status:
            1 - I have stocks, I need to choose sell or not: if prices[i] > prices[i+1] then sell
            2 - I do not have stocks, I need to choose buy or not: if prices[i] < prices[i+1] then buy
        """
        # Initially, we do not have any stock
        has_stock = False
        total_profit = 0
        buy_price = 0
        for i in xrange(len(prices)-1):
            if has_stock:
                if prices[i] > prices[i+1]:
                    total_profit += prices[i] - buy_price
                    has_stock = False
            else:
                if prices[i] < prices[i+1]:
                    buy_price = prices[i]
                    has_stock = True
        if has_stock:
            total_profit += prices[-1] - buy_price
        return total_profit