leetcode121 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.
"""
class Solution1(object):
    def maxProfit(self, prices):
        if prices == None or len(prices) < 1:  #先对边界判断,提升代码质量
            return 0
        n = len(prices)
        max_profit = 0
        for i in range(n):
            for j in range(i+1, n):
                if (prices[j] - prices[i]) > max_profit:
                    max_profit = prices[j] - prices[i]
        return max_profit

"""
这是dp题,此暴力方法超时。
[10000,9999,9998,9997,9996,...,1]用例超时
"""

"""
解法二:维护两个指标:buy和sell
去min(buy), max(sell)
花最少的本钱,获得最多的利润
进行一次遍历
"""
class Solution2(object):
    def maxProfit(self, prices):
        if prices == None or len(prices) < 1: #边界条件
            return 0
        buy = prices[0]    #买的初始化为第一个价格
        sell = 0           #利润初始化为0
        for i in range(1, len(prices)):  #从第二个价格开始向后遍历
            buy = min(buy, prices[i])    #找最小的进价
            sell = max(sell, prices[i] - buy)  #更新可以获得的最大利润
        return sell

 

posted @ 2020-02-04 22:07  yawenw  阅读(128)  评论(0编辑  收藏  举报