题目:
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
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)