0
点赞
收藏
分享

微信扫一扫

Leetcode-买卖股票的最佳时机

妖妖妈 2022-03-13 阅读 56

在这里插入图片描述
一开始直接蛮力枚举。。。。:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        d = 0
        for i in range(len(prices)):
            for j in range(i,len(prices)):
                if(prices[j]-prices[i]>d):
                    d = prices[j]-prices[i]
        return d

醉了。。。
在这里插入图片描述
还是得用动态规划的思想来做,但一开始确实是没找出来。。。

分析: 前 i 天的最大收益依赖于前 i-1 天的最大收益,和第 i 天的收益减去前 i-1 天中的最小买入价格,两个比较取最大,所以递推式为 d[i] = max{d[i-1] , i - min(i-1)}

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        d = 0      ##记录当前最大收益
        mi = prices[0]     ## 记录前i-1天中最小买入价格
        for i in range(1,len(prices)):
            if(d<(prices[i])-mi):
                d = prices[i]-mi
            elif(prices[i]<mi):
                mi = prices[i]
        return d

提交通过:
在这里插入图片描述

所以说,动态规划找到递推式很重要,继续练吧。小记,干巴爹!💪

举报

相关推荐

0 条评论