zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    数据结构之双向链表
    数据结构入门之链表(C语言实现)
    机器人操作臂运动学入门一--D-H参数标定
    机器学习--逻辑回归
    python字符串方法的简单使用
    python学习之网页数据获取
    《机器学习实战》学习笔记一K邻近算法
    杂事
    洛谷 P1926 小书童——刷题大军
    洛谷 P1968 美元汇率
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14638902.html
Copyright © 2011-2022 走看看