假设你有一个数组prices,长度为n,其中prices[i]是股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1.你可以买入一次股票和卖出一次股票,并非每天都可以买入或卖出一次,总共只能买入和卖出一次,且买入必须在卖出的前面的某一天
2.如果不能获取到任何利润,请返回0
3.假设买入卖出均无手续费
数据范围: 
要求:空间复杂度
,时间复杂度 )
[8,9,2,5,4,7,1]
5
在第3天(股票价格 = 2)的时候买入,在第6天(股票价格 = 7)的时候卖出,最大利润 = 7-2 = 5 ,不能选择在第2天买入,第3天卖出,这样就亏损7了;同时,你也不能在买入前卖出股票。
[2,4,1]
2
[3,2,1]
0
class Solution: def maxProfit(self , prices ): # write code here res=[0]*len(prices) for i in range(2,len(prices)+1): res[-i]=max(res[-i],prices[1-i]+res[1-i]-prices[-i]) return max(res)用动态规划的思路倒推每天买入后的最大收益值
# # # @param prices int整型一维数组 # @return int整型 # class Solution: def maxProfit(self , prices ): # write code here if not prices&nbs***bsp;prices==1: return 0 min_p=prices[0] money=0 max_m=0 for p in prices: money = p-min_p if money<0: min_p=p if money>max_m: max_m=money return max_money
# @return int整型 # class Solution: def maxProfit(self , prices ): # write code here maxval=0 length=len(prices) for i in range(1,length): flag=max(prices[i:])-min(prices[:i]) if flag>maxval: maxval=flag return maxval
class Solution: def maxProfit(self , prices ): # write code here if not prices: return 0 n = len(prices) buy_t = sale_t = 0 res = prices[sale_t] - prices[buy_t] for t in range(n): if prices[t] > prices[sale_t]: sale_t = t res = max(res, prices[sale_t] - prices[buy_t]) elif prices[buy_t] <= prices[t] <= prices[sale_t]: continue else: buy_t = t sale_t = t return res
class Solution: def maxProfit(self , prices ): # write code here result = 0 for i in range(len(prices)-1): if max(prices[i+1:]) - prices[i] > result: result = max(prices[i+1:]) - prices[i] return result
#动态规划,python #第i天可能获得的最大利润 = max( 第i-1天可能获得最大利润 , # 第i天prices最高时卖出可能获得最大利润) class Solution: def maxProfit(self , prices ): # write code here if len(prices) <= 1: return 0 a = [0]*len(prices) for i in range(1,len(prices)): a[i] = max(a[i-1],prices[i]-min(t for t in prices[:i])) return a[-1]
class Solution: def maxProfit(self , prices ): # write code here if len(prices)==2: return max(prices[1]-prices[0],0) num = 0 out = 0 # 如果:收益(第0天买入第2天卖出)>收益(第1天买入第2天卖出) # 那么一定有:收益(第0天买入第n天卖出)>收益(第1天买入第n天卖出) n>2 # 所以每增加一天只需比较:收益(第num天买入第n天卖出)与 收益(第n-1天买入第n天卖出) # 如果:收益(第num天买入第n天卖出)< 收益(第n-1天买入第n天卖出) # 则:num = n-1 for i in range(1,len(prices)): if prices[i]-prices[num]<prices[i]-prices[i-1]: num = i-1 dp = prices[i]-prices[i-1] else: dp = prices[i]-prices[num] out = max(dp,out) return out
注意你不能在买入股票前卖出股票
输入: [7,1,5,3,6,4]