121. Best Time to Buy and Sell Stock [easy] (Python)

题目链接

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

题目原文

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

题目翻译

假设有一个数组,它的第i项是第i天的股票价格。如果你最多只能进行一次买卖操作(买一次,卖一次),设计一个算法求出最大的收益。

思路方法

直观的理解,就是求数组中 max(array[j]-array[i]), j>=i。用两重循环求出每一对不同i,j的差值,这样做会超时,所以要用更巧妙的方法。

思路一

实际上,一次循环就可以求出结果。在遍历的过程中,用一个变量保存目前为止最小的数,用当前的数与目前最小的数相减,判断这个差与此前得到的最大收益的大小,取较大值更新最大收益。

代码

class Solution(object):
    def maxProfit(self, prices):
        """ :type prices: List[int] :rtype: int """
        if len(prices) == 0:
            return 0
        minPrice = prices[0]
        maxProfit = 0
        for p in prices:
            if p < minPrice:
                minPrice = p
            elif p - minPrice > maxProfit:
                maxProfit = p - minPrice
        return maxProfit

思路二

实际上,这道题本质上是个动态规划问题。如果上面的代码不太好理解,可以尝试理解下面的代码。

代码

class Solution(object):
    def maxProfit(self, prices):
        """ :type prices: List[int] :rtype: int """
        if len(prices) == 0:
            return 0
        minPrice = prices[0]
        dp = [0] * len(prices)
        for i in xrange(0, len(prices)):
            dp[i] = max(dp[i-1], prices[i] - minPrice)
            minPrice = min(minPrice, prices[i])
        return dp[-1]

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51520971

    原文作者:coder_orz
    原文地址: https://blog.csdn.net/coder_orz/article/details/51520971
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞