• Leetcode 121. Best Time to Buy and Sell Stock


    Description: You are given an array prices where prices[i] is the price of a given stock on the ith day.

    You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

    Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

    Link: 121. Best Time to Buy and Sell Stock

    Examples:

    Example 1:
    Input: prices = [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.
    Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
    
    Example 2:
    Input: prices = [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transactions are done and the max profit = 0.

    思路: 股票在这个序列中只交易一次,也就是只买卖一次,求最大收益。两层循环逐个比较一定会超时,所以dp记录,记录什么呢?记录第i天后出现的最大值,这样就知道第i天能卖出的最高价格,最后一天之后的最大值是自己,依次向前推,倒数第二天后出现的最大值dp[n-2] = max(prices[n-2], dp[n-1]),直到第一天。

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            n = len(prices)
            if n <= 1: return 0
            res = 0
            dp = [0]*n # maximum value after i_th day
            dp[-1] = prices[-1]
            for i in range(2, n+1):
                dp[n-i] = max(prices[n-i], dp[n-i+1])
                res = max(res, dp[n-i]-prices[n-i])
            return res

    另一种就是记录第i天的最好收益,注意不一定是第i天卖出,也可能是之前就卖出了,同时记录i天前的最低价格,这样dp[i] = max(dp[i-1], prices[i]-minPrices)

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            n = len(prices)
            if n <= 1: return 0
            minprice = prices[0]
            dp = [0]*n # maximum benefit at i_th day
            for i in range(1, n):
                minprice = min(minprice, prices[i])
                dp[i] = max(dp[i-1], prices[i]-minprice)
            return dp[-1]

    日期: 2021-04-09

  • 相关阅读:
    Unity3D 学习笔记
    Python中os和sys模块
    合并两个排序的链表
    反转链表 难
    链表中倒数第k个结点
    调整数组顺序使奇数在偶数前 14
    javascript中this详解
    静态方法实例方法
    强制类型转换
    javascript类型判断方法
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14638902.html
Copyright © 2020-2023  润新知