leetcode 121.best-time-to-buy-and-sell-stock 买卖股票的最佳时机 python3

时间:2020-5-16

题目地址:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/

题目难度:Easy

题目描述:

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。

注意:你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。


思路1:暴力破解

代码段1:超过执行时间

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        result = 0
        if(len(prices) == 1): return result
        for i in range(0, len(prices)-1):
            for j in range(i+1, len(prices)):
                if(prices[i] < prices[j]):
                    temp = prices[j] - prices[i]
                    result = max(result, temp)
        return result

总结:

  1. 199/200通过,下次使用双循环暴力破解的时候一定要慎重,leetcode一定会给你留一个用例用来跑时间复杂度

思路2:和之前做过的leetcode 53.maximum-sum-subarray最大子序和一样,当双层for循环时需要考虑从零开始,你是不是真的需要双层for循环

代码段2:执行通过

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        result = 0
        if(len(prices) == 1 or len(prices) == 0): return result
        high, low = 0, prices[0]
        for i in range(0, len(prices)):
            temp = prices[i]
            low = min(low, temp)
            high = max(high, temp - low)
        return high

总结:

  1. 不断地写代码考虑各种特殊场景,代码非常冗余。
  2. 看到官方解法对于float('inf')正无穷,float('-inf')负无穷用的特别好,为代码减压,能使代码优雅不少。上个代码段和下边我使用正无穷后的执行用时、内存消耗分别为    48 ms    14.7 MB |  56 ms    14.6 MB
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        high, low = 0, float('inf')
        for price in prices:
            low = min(low, price)
            high = max(high, price - low)
        return high

后续优化:

动态规划

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值