[LeetCode] [Python] [DP] Best Time to Buy and Sell Stock

3 篇文章 0 订阅
3 篇文章 0 订阅

题目:

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.

意思:
给你一串数列代表第i天的价格,你只有一次买入卖出机会,求最大盈利。

首先明确一点:这道题目是很明显的DP问题,当然你也可以用暴力求解求出每个f(i,j) i天买入j天卖出然后求最大值
这是最差的方法,我就不提了,接下来说说dp。

这道题目的转移方程比较简单就能给出 设数列为k,f(n)代表第N天卖出的最大收益

f(n) = kn-minRange(0,n-1)  最后结果为 result = max(f(2...n),0) 这里说明一点,我个人认为这里的转移是在求最小值即

minRange(0,i) = min(minRange(0,i-1), num[i]) 而不是直接求得结果,可能不同人理解不一样

那么仅看这个转移方程我们能有

n = len(prices)
ma = 0
for i in range(n) :
    for j in range(i+1) :
        ma = max(ma,prices[i]-prices[j])
return ma


我们可以观察发现实际上每次都循环找到最小值是没必要的因为我们在循环过程中只要每次记录下当前以及之前数列中的最小值那么f(i)=prices[i]-minNum也就是当前值减去最小值就可以了,然后每次又用变量存储下f(i)与之前值得最大值即可,因此优化后的最终代码为:

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        if len(prices) < 1 :
            return 0
        mi = prices[0]
        ma = prices[0]
        got = 0
        for i in range(1,len(prices)) :
            got = max(got,prices[i]-mi) #找最大收益的过程
            mi = min(mi,prices[i])  #找最小值的过程
        return got

时间复杂度O(n) 空间复杂度O(1)




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值