第二十六天 Best Time to Buy and Sell Stock

今天这两道题做的不是很顺利

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

拿到这道题,最朴素的想法,就是两重循环,暴力的去尝试下每种结果

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        ret = 0
        for i in range(0,len(prices)):
            for j in range(i,len(prices)):
                temp = prices[j] - prices[i]
                if temp > ret:
                    ret = temp
        return ret

这个显然不符合时间要求,会超时

那么接下来,其实冷静下来想一下,其实我可以维护两个值,一个是买入价和一个是卖出价,当一支股票低过我的买入价的时候我就可以考虑买入,他就是我新的买入价,如果是高过我的买入价,他就是我新的卖出价,这个时候我就能得到我的收益,那么就需要再用一个值来保存下我的收益值,比较一下

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        buyingPrice = sys.maxsize
        sellingPrice = 0
        netProfile = 0
        for stock in prices:
            if stock < buyingPrice:
                buyingPrice = stock
            if stock > buyingPrice:
                sellingPrice = stock
                if sellingPrice - buyingPrice > netProfile:
                    netProfile = sellingPrice - buyingPrice
        return netProfile

你可能感兴趣的:(第二十六天 Best Time to Buy and Sell Stock)