[LeetCode][Python]121. 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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

思路1:

采取动态规划中的Kadane算法,采用两个数分别记取当前最大值curMax和截止到现在最大值sofarMax,以此从1开始遍历list。比较0和curMax加上prices[i]-prices[i-1],以后的处理就和Maximum Subarray类似了。

对于每一个阶段来说,我们只关注一个状态:当前元素减去上一元素的值。对于每个阶段来说,值最大的那个差值,就是局部最优解。在转移过程中,如果上一阶段的最优解小于0,则直接重设为0;如果不小于0,则只需要在上一阶段的局部最优解的基础上,加上下一个差值即可。

思路2:采取两个数保存最小价格min_prices和最大利润max_profit,依次遍历list,如果有比当前价格小的,赋给min_prices,profit就是price-prize,如果有比当前利润大的,就赋给maxprofit。Python中可以用如下方式表示正负无穷:float("inf"), float("-inf")。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        curMax = sofarMax = 0
        for i in xrange(1, len(prices)):
            curMax = max(0, curMax + prices[i] - prices[i-1])
            sofarMax = max(curMax, sofarMax)
        return sofarMax

    def maxProfit2(self, prices):
        if len(prices) < 2:
            return 0
        buy, sale, profit = prices[0], 0, 0

        for i in xrange(1,  len(prices)):
            if prices[i] < buy:
                buy = prices[i]
            elif prices[i] > buy:
                sale = prices[i]
                if sale - buy > profit:
                    profit = sale - buy
        if sale == 0:
            profit = 0
        return profit

    def maxProfit3(self, prices):
        max_profit, min_price = 0, float('inf')
        for price in prices:
            min_price = min(min_price, price)
            print 'min price', min_price
            profit = price - min_price
            max_profit = max(profit, max_profit)
            print 'max profit', max_profit


        return max_profit

if __name__ == '__main__':
    sol = Solution()
    s = [7, 1, 5, 3, 6, 4]
    # the expect result is 5 (6-1)
    print sol.maxProfit(s)
    print sol.maxProfit2(s)
    print sol.maxProfit3(s)

    s2 = [7, 6, 4, 3, 1]
    # the expect result is 0
    print sol.maxProfit(s2)
    print sol.maxProfit2(s2)

补充:设置游标记取最小价格,然后比较每个价格和这个最小价格的差值,其中最大的值就是我们的最大盈利。

    def maxProfit4(self, prices):
        res = 0
        low = float('inf')
        for i in xrange(len(prices)):
            if prices[i] < low:
                low = prices[i]
            res = max(res, prices[i]-low)

        return res

你可能感兴趣的:([LeetCode][Python]121. Best Time to Buy and Sell Stock)