您的位置:首页 > 编程语言 > Python开发

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

2014-10-27 20:52 337 查看
题目:
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python DP leetcode