Leetcode 121. Best Time to Buy and Sell Stock

本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。该算法通过一次遍历找到最低买入价格,并据此计算出最大可能利润。同时,提供了一个逆向思路,即先计算后续最高价格再求最大利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

 

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

 

如果当前时刻 i 买入,那么对应于这个买入所能达到的最大收益就是当前价格和之后所有价格的max之间的差。所以我们要求一个maxPriceAfter list,来存储i之后的最高价格。显然只要倒叙求一遍max最大值就可以。

 

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7             
 8         n = len(prices)
 9         if n <= 1:
10             return 0
11         
12         maxPriceAfter = [0]*n
13         maxPriceAfter[-1] = prices[-1]
14         
15         peak = prices[-1]
16         for i in range(n-1, -1, -1):
17             peak = max(peak, prices[i])
18             maxPriceAfter[i] = peak
19         
20         maxProfit = 0
21         
22         for i in range(n):
23             maxProfit = max(maxProfit, maxPriceAfter[i]-prices[i])
24         
25         return maxProfit

或者维护一个从最开始到当前时刻的最低价格,当年价格减去这个最低价格就是当前卖出所能达到的最高利润。

 

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
            
        n = len(prices)
        if n <= 1:
            return 0
        
        lowPrices = prices[0]
        
        maxProfit = 0
        
        for i in range(n):
            lowPrices = min(lowPrices, prices[i])
            maxProfit = max(maxProfit, prices[i]-lowPrices)
            
        return maxProfit

 

转载于:https://www.cnblogs.com/lettuan/p/6854753.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值