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

  • 相关阅读:
    无线网络技术知识点
    中国高校计算机大赛—网络技术挑战赛
    实验二 软件工程个人项目
    实验一 软件工程准备
    2018年春季软件工程教学设计(初稿)
    2017-2018春季学期软件工程教学资源目录
    2017-2018春季学期软件工程教学纲要
    如何解决Android Studio解决DDMS真机/模拟器无法查看data目录问题
    GitHub的Windows客户端的使用教程
    2017面向对象程序设计(JAVA)课程总结
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14638902.html
Copyright © 2011-2022 走看看