[leetCode刷题笔记]2017.02.18

来源:互联网 发布:大数据用什么软件 编辑:程序博客网 时间:2024/06/06 06:41
时间一天比一天紧了,下星期有个biotech的面试,要用python和linux。。。。额我好久没用python了,linux太水。哎,咋办呢?最近几天刷题用python吧。


121. Best Time to Buy and Sell Stock
动态规划,保存最小值,再找出对应的最大profit
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0:
            return 0
        
        # min price and max profit
        minPrice = prices[0]
        maxProfit = 0
        
        for i in range(len(prices)):
            if prices[i] < minPrice:
                minPrice = prices[i]
            if prices[i] - minPrice > maxProfit:
                maxProfit = prices[i] - minPrice
        
        return maxProfit





122. Best Time to Buy and Sell Stock II
贪心算法,碰到prices[i +1] > prices[i]情况就卖掉,注意边界情况。
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        if prices is None or len(prices) < 2:
            return 0
        
        buy = 0
        sell = 0
        profit = 0
        
        for i in range(len(prices) - 1):
            if (prices[i + 1] >= prices[i]):
                sell = i + 1
            else:
                
                profit = profit + (prices[sell] - prices[buy])
                buy = i + 1
                sell = i + 1
                

        return profit + max(0, (prices[sell] - prices[buy]))

123. Best Time to Buy and Sell Stock III

有点难的题目,根据i的位置,动态将数组分成两个部分,并用p1存贮i之前的最大利润p2存储i之后的最大利润。最后求p1[i] + p2[i]的最大值。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if n <= 1:
            return 0
        # generate two arrays
        # max profit before i
        p1 = [0] * n
        # max profit after i
        p2 = [0] * n
        
        minV = prices[0]
        
        for i in range(1, n):
            minV = min(minV, prices[i])
            p1[i] = max(p1[i - 1], prices[i] - minV)
            
        maxV = prices[-1]
        
        for i in range(n -2, -1, -1):
            maxV = max(maxV, prices[i])
            p2[i] = max(p2[i +1], maxV - prices[i])
            
        result = 0
        
        for i in range(n):
            result = max(result, p1[i] + p2[i])
            
        return result

217. Contains Duplicate

用一个map,每循环一个,看map里面有没有,有的话false没有的话加入map

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        map = {}
        for i in nums:
            if i in map:
                return True
            map[i] = True
        return False
            

0 0
原创粉丝点击