LeetCode解题报告:121. Best Time to Buy and Sell Stock

Problem

Say you have an array for which the i t h i^{th} ith element is the price of a given stock on day i.

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

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [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.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解题思路

   这一题只允许我们进行一次交易,然后要求交易的获利最大。有一个很自然的想法,我们让变量 i i i从头开始遍历,并让变量 j j j i i i开始遍历,这样依次去进行交易,然后取所有可能的交易获利中的最大值。这样的方法时间复杂度是 O ( N 2 ) O(N^2) O(N2),对于大量的数据来说有些太慢了。

  因此,我们考虑使用一个数组来保存一个递增序列,表示可能遇到的可交易的时间点,在当前的时间节点的交易值前面,如果当前的序列中,最后一个节点的交易数值大于当前值,说明这个节点不是我们需要的,将其弹出,接着对数组中的下一个数据进行处理,直到数组为空或者数组最后一个节点小于等于当前的交易值,然后用数组的尾节点减去首节点就是在当前节点可以获得的最大获利。这个方法可以通过测试,空间复杂度不算太高,一般小于 O ( N ) O(N) O(N),时间复杂度也不算很高,接近 O ( N l o g N ) O(NlogN) O(NlogN)

  代码如下:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        money = 0
        stack = []
        for n in prices:
            while stack and n < stack[-1]:
                stack.pop(-1)
            stack.append(n)
            money = max(money, stack[-1] - stack[0])
        return money

  在代码中我们维持了一个递增数组,并且每次都还是要弹出数据或者弹入数据,而且真正用的上的也就是数组中的第一个数据和最后一个数据,因此,我们可不可以考虑不用保存这个数组呢?其实是可以的,我们只需要在合适的时候判断一下即可,道理和上面的代码完全一致,只不过省略了数组结构,并且空间复杂度为常数,时间复杂度为 O ( N ) O(N) O(N)

   代码如下:

class Solution:
    def maxProfit(self, prices):
        buy, profit = float('inf'), 0
        for p in prices:
            if p < buy: 
            	buy = p
            elif p - buy > profit: 
            	profit = p - buy
        return profit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值