Tencent 47-the best time to buy and sell stocks

Tencent 47-the best time to buy and sell stocks

Given an array, the i-th element is the price of the i-th day of a given stock.

If you are only allowed to complete one transaction at most (ie buying and selling one stock), design an algorithm to calculate the maximum profit you can get.

Note that you cannot sell stocks before buying them.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on the 2nd day (stock price = 1), sell on the 5th day (stock price = 6), Maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.

analysis:

  • The stock requirements here, buy before sell
  • Buy and sell two variables, if you use dp [i] [j], it is o (n * n), which is equivalent to violence and is not desirable
  • Because the stock will be sold sooner or later, even if the final result is 0, which is equivalent to not selling, it can be considered to be sold on the 0th day
  • So use dp [i] to represent the maximum gain if you sell stocks on the i-th day, dp [0] = 0, if there is no income on the first day, it only makes sense from dp [1]
  • dp [i] means that if you sell stock on the i-th day, you must definitely subtract the previous minimum value, so all use a min_cur, which means the end of the i-day, including the minimum value of the i-day
  • In summary, res is the maximum value in dp [i]
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        #这里股票要求,先买后卖
        #买卖两个变量,如果用dp[i][j],就是o(n*n),等同于暴力
        #因为股票迟早要卖的,即使最后结果是0,相当于不卖,可认为是第0天卖的
        #所以用dp[i]表示如果第i天卖股票,能获得的最大收益,dp[0]=0,第一天没收入的,从dp[1]开始才有意义
        #dp[i]表示如果第i天卖股票,肯定要减去之前的最小值,所有用一个min_cur,表示截止第i天,包括第i天的最小值
        #综上,res就是dp[i]中的最大值
        if len(prices)==0 or len(prices)==1:return 0
        else:
            res=0
            min_cur,dp=prices[0],[0]
            for i in range(1,len(prices)):
                min_cur=min(min_cur,prices[i])
                dp.append(prices[i]-min_cur if prices[i]-min_cur>0 else 0)
                res=max(res,dp[-1])
        return res
Published 93 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/zlb872551601/article/details/103652624