leetcode.122.Best Time to Buy and Sell Stock II

来源:互联网 发布:北京交通大学知行bt 编辑:程序博客网 时间:2024/06/06 03:51

Description

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).

sln1

我们将股票的价格与日期之间的关系以一条折线来表示,那么只要我们在折现的极小值处买入并在接下来的一个极大值处卖出。重复这样的操作,就能保证到最后获利最高。那么问题就变成如何确定这个极大值和极小值了。我采取的方法是用一个flag来记录当前股票的走势是下降还是上升(has_stock),然后根据今天和明天股票价格的大小关系,便能判断今天的价格点是否是极值点,如果是的话再根据前面提到的flag来判断是极大值还是极小值。另外一个要注意的地方是,当分析到最后一天的股票价格的时,我们无法根据后一天的价格来进行判断,那么如果此时股票走势是上升的(has_stock=True),我们则无论如何都要卖掉股票。而如果此时股票走势是下降的,说明此时我们并不持有股票,因此我们也不会买入股票。python实现如下:

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        earn = 0        buy_in_price = 0        has_stock = False        for pidx, price in enumerate(prices[:-1]):            tommorrow_price = prices[pidx + 1]            if tommorrow_price > price and not has_stock:                buy_in_price = price                has_stock = True            elif tommorrow_price < price and has_stock:                earn += (price - buy_in_price)                has_stock = False        if has_stock:            earn += (prices[-1] - buy_in_price)        return earn

提交结果后时间超过75%+的用户,时间复杂度为O(n)。于是我又去Discussion中看看其他大牛是如何用低于O(n)的时间解决这个问题的。

sln2

大概看了Discussion前面几个答案后,发现大家的时间复杂度都是O(n),并且发现一个十分有趣的解决方法。
从sln1中我们可以看出,该算法认为我们只有在卖出股票的时候才有盈利,然而因为我们已经知道未来的股票价格了,这意味着每一天只要股票上涨,我们就是在盈利的,同时我们会在股票下跌之前就卖出股票,避免亏损。因此,我们只要计算每天股票上涨能给我们带来多少盈利,并把他们全部加起来,就是我们的最大盈利了。这种解决思路可以用一行python代码来实现,代码如下:

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        return sum(map(lambda x, y:max(y - x, 0), prices[:-1], prices[1:]))
0 0
原创粉丝点击